从 HashMap<Integer, List<Object>> 使用 Java8 概念过滤值

Filter values from HashMap<Integer, List<Object>> using Java8 concepts

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

我的期望:
使用 Java8 流概念提取 HashMap<Integer, List<Parent>> 的子集,其中 List 中的对象是 instaceOf Child Class 和 finder Child class 的属性有一个具体值(例如测试)

示例:
输入

{
1=[Child [finder=test], Parent [], Child [finder=test]],
2=[Child [finder=text], Parent [], Parent []],
3=[Child [finder=test], Child [finder=test], Parent []]
}

输出

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

代码

下面是我的 class 结构,其中有 Parent class 和一个 Child class。还有 Hashmap 对象,其中键是一个整数,值是 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 + "]";
    }
}

测试数据

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()));

进程

  • 首先将映射条目映射到键的各个条目和列表的每个值元素。
  • 然后过滤 Child 和查找器类型的实例。
  • 键(整数)上的组并将children放入列表
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 class 中添加了 getter 以检索查找器值。