java-8 - 从 HashMap 过滤值> 使用 Java8 概念
问题描述
我的输入:
具有结构的哈希图,HashMap<Integer, List<Parent>>
其中List<Parent>
可以包含子对象的实例。
我的期望:
使用 Java8 流概念提取HashMap<Integer, List<Parent>>
List 中的对象的子集是instaceOf Child
Class 并且 finder
Child 类的属性具有特定值(例如 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 + "]";
}
}
解决方案
测试数据
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 值。
推荐阅读
- python - 如何创建 datetime.time 类的子类
- laravel - 如何修复未定义函数:7 错误:运算符不存在:整数 = 文本
- javascript - 如何将 Python+Flask 对象列表转换为 JS 对象列表?
- python - Python:尝试检查文件是否存在,如果不存在,则创建新文件和最终输出列表
- reactjs - 盖茨比:更改默认路径名称
- javascript - (let { items } = user) 是否与说 (user.items) 完全相同?
- c - 返回指向 const int 的 const 指针
- python - 如何在 Windows PC 上安装 pygalmesh(取决于 Eigen)?
- python - 如何连接以字母开头的行?
- arrays - 来自红宝石哈希值的笛卡尔积