> 使用 Java8 概念,java-8,stream"/>

首页 > 解决方案 > 从 HashMap 过滤值> 使用 Java8 概念

问题描述

我的输入:
具有结构的哈希图,HashMap<Integer, List<Parent>>其中List<Parent>可以包含子对象的实例。

我的期望:
使用 Java8 流概念提取HashMap<Integer, List<Parent>>List 中的对象的子集是instaceOf ChildClass 并且 finderChild 类的属性具有特定值(例如 test)

示例:
输入

{
1=[子 [finder=test], 父 [], 子 [finder=test]],
2=[子 [finder=文本], 父 [], 父 []],
3=[子 [finder=test ] ],子 [finder=test],父 []]
}

输出

{
1=[子 [finder=test],子 [finder=test]],
3=[子 [finder=test],子 [finder=test]]
}

代码

下面是我的班级结构,其中有Parent class一个Child class. 还有一个Hashmap对象,其中 key 是 Integer 并且 value 是List<Parent>

class Parent {

    @Override
    public String toString() {
        return "Parent []";
    }
}

class Child extends Parent{
    public String finder;
    
    public Child(String f) {
        this.finder = f;
    }
    @Override
    public String toString() {
        return "Child [finder=" + finder + "]";
    }
}

标签: java-8stream

解决方案


测试数据

Map<Integer, List<Parent>> map = new HashMap<>();
map.put(1, List.of(new Child("test"),new Parent(),
        new Child("test"), new Child("Foo"), new Parent()));
map.put(2, List.of(new Parent(), new Child("text")));
map.put(3, List.of(new Parent(), new Child("Bar"), 
        new Child("test"), new Parent()));

过程

  • 首先将映射条目映射到键的各个条目和列表的每个值元素。
  • 然后过滤子实例和查找器类型。
  • 键上的组(整数)并将孩子放入列表中
Map<Integer, List<Parent>> map2 = map.entrySet().stream()
        .flatMap((Entry<Integer, List<Parent>> e) -> e
                .getValue().stream()
                .map(v -> new AbstractMap.SimpleEntry<>(
                        e.getKey(), v)))
        .filter(obj -> obj.getValue() instanceof Child && 
                ((Child)obj.getValue()).getFinder().equals("test"))
        .collect(Collectors.groupingBy(Entry::getKey,
                Collectors.mapping(Entry::getValue,
                        Collectors.toList())));

map2.entrySet().forEach(System.out::println);

印刷

1=[Child [finder=test], Child [finder=test]]
3=[Child [finder=test]]

我在 Child 类中添加了一个 getter 来检索 finder 值。


推荐阅读