【发布时间】:2017-04-21 03:27:24
【问题描述】:
我有两个流,我想将它们组合成不同的列表 即我有哈希图
Map<String, List<String>> citiesByZip = new HashMap<>();
持有这些数据
Alameda [95246, 95247]
Colusa [95987]
人员名单
class Person {
private String firstName;
private String lastName;
private int income;
private int zipCode;
People(String firstName, String lastName, int income, int zipCode) {
this.firstName = firstName;
this.lastName = lastName;
this.income = income;
this.zipCode = zipCode;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getIncome() {
return income;
}
public int getZipCode() {
return zipCode;
}
}
List<Person> persons= new ArrayList<>();
持有这些数据的人
Junior Jane 20000 95246
Junior Jane 30000 95246
Joseph James 50000 95247
Patricia Allen 60000 95247
Opal Campbell 70000 95987
Dorothy Rook 80004 95987
Mary Nelson 80000 23666
我想将列表中的每个人映射到县的 hashmap 以查找居住在哪个县的人
List <FinalObject> finalObjects= new ArrayList<>();
finalObjects = Stream.concat(peopleStream.stream(), citiesByZip.entrySet().stream())
.collect(Collectors.toMap(
))
这个列表应该返回最终对象的列表 像这样
Junior Jane 20000 Alameda
Junior Jane 30000 Alameda
Joseph James 50000 Alameda
.
.
etc
我知道我可以在 Java 7 中使用传统循环来完成这项工作,但我想知道我是否可以在 Java 8 中使用 stream and lambda 做同样的事情
【问题讨论】:
-
给我们(可编译的)样本数据来处理。
-
我认为您需要一张地图,其键是邮政编码,其值是与该邮政编码相关的城市。
-
@Alexander 完全正确,但我不知道如何在其他流中引用流
-
给我们(可编译的)样本数据来处理。
-
@kero 在不相关的说明中,您的
citiesByZip地图实际上更像zipsByCity(邮政编码是按城市查找的,而不是您的名字所暗示的其他方式)。另外,请查看来自 Google 的 Guava 库的Multimap。它非常适合您的用例(为每个城市键映射多个邮政编码值)。有一些方法可以“反转”多张地图,可以在给定zipsByCity的情况下生成citiesByZip地图
标签: java-8 java-stream