我有以下问题:给定这些类,
class Person {
private String zip;
...
public String getZip(){
return zip;
}
}
class Region {
private List<String> zipCodes;
...
public List<String> getZipCodes() {
return zipCodes;
}
}
使用Java 8 Stream API,如何根据Map<Person, List<Region>>
是否包含Region
的邮政编码获取Person
?换句话说,如何通过邮政编码属于这些区域的人对区域进行分组?
我在Java 7中用老式的方式完成了它,但现在我必须迁移代码以利用Java 8中的新功能。
谢谢,
英佩特
答案 0 :(得分:5)
我怀疑这是最干净的方式 - 我对发布的其他答案不太满意 - 会是
persons.stream().collect(Collectors.toMap(
person -> person,
person -> regions.stream()
.filter(region -> region.getZipCodes().contains(person.getZip()))
.collect(Collectors.toList())));
答案 1 :(得分:2)
原始答案使用元组进行不必要的映射,因此您可以看到最终解决方案。您可以删除映射,只需直接过滤regions
列表:
//A Set<Region> is more appropriate, IMO
.stream()
.collect(toMap(p -> p,
p -> regions.stream()
.filter(r -> r.getZipCodes().contains(p.getZip()))
.collect(toSet())));
<小时/> 如果我理解得很好,你可以这样做:
import java.util.AbstractMap.SimpleEntry;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toList;
...
List<Person> persons = ...;
List<Region> regions = ...;
Map<Person, List<Region>> map =
persons.stream()
.map(p -> new SimpleEntry<>(p, regions))
.collect(toMap(SimpleEntry::getKey,
e -> e.getValue().stream()
.filter(r -> r.getZipCodes().contains(e.getKey().getZip()))
.collect(toList())));
从List<Person>
获得Stream<Person>
。然后,将每个实例映射到包含所有区域的元组<Person, List<Region>>
。从那里,您使用toMap
收集器在地图中收集数据,并为每个人构建一个包含该人的邮政编码的Region
列表。
例如,给定输入:
List<Person> persons = Arrays.asList(new Person("A"), new Person("B"), new Person("C"));
List<Region> regions =
Arrays.asList(new Region(Arrays.asList("A", "B")), new Region(Arrays.asList("A")));
输出:
Person{zip='A'} => [Region{zipCodes=[A, B]}, Region{zipCodes=[A]}]
Person{zip='B'} => [Region{zipCodes=[A, B]}]
Person{zip='C'} => []
另外,我猜每个zipCodes
的{{1}}可能是Region
。
答案 2 :(得分:1)
我没有对此代码进行了任何测试,但它编译所以必须正确(:eyeroll :)。
public Map<Person,List<Region>> mapPeopleToRegion(List<Person> people, List<Region> regions){
final Map<Person,List<Region>> personToRegion = new HashMap<>();
people.forEach(person ->
personToRegion.put(
person,regions.stream().filter(
region -> region.getZipCodes().contains(person.getZip()))
.collect(Collectors.toList())));
return personToRegion;
}
答案 3 :(得分:0)
它仍然非常丑陋,我认为通过改变你的模型来改善它会有所改进,但到目前为止我只能设法得到以下内容:
public static void main(String[] args) {
Person[] people = {new Person("00001"), new Person("00002"), new Person("00005")};
Region[] regions = {
new Region("Region 1", Arrays.asList("00001", "00002", "00003")),
new Region("Region 2", Arrays.asList("00002", "00003", "00004")),
new Region("Region 3", Arrays.asList("00001", "00002", "00005"))
};
Map<Person, List<Region>> result = Stream.of(regions)
.flatMap(region -> region.getZipCodes().stream()
.map(zip -> new SimpleEntry<>(zip, region)))
.flatMap(entry -> Stream.of(people)
.filter(person -> person.getZip().equals(entry.getKey()))
.map(person -> new SimpleEntry<>(person, entry.getValue())))
.collect(Collectors.groupingBy(Entry::getKey, Collectors.mapping(Entry::getValue, Collectors.toList())));
result.entrySet().forEach(entry -> System.out.printf("[%s]: {%s}\n", entry.getKey(), entry.getValue()));
// Output:
// [Person: 0]: {[name: Region 1, name: Region 3]}
// [Person: 1]: {[name: Region 1, name: Region 2, name: Region 3]}
// [Person: 2]: {[name: Region 3]}
}
拥有一个包含映射并且可以键入的ZipCode
类可以使事情更清晰:
public static void main(String[] args) {
Region r1 = new Region("Region 1");
Region r2 = new Region("Region 2");
Region r3 = new Region("Region 3");
ZipCode zipCode1 = new ZipCode("00001", Arrays.asList(r1, r3));
ZipCode zipCode2 = new ZipCode("00002", Arrays.asList(r1, r2, r3));
ZipCode zipCode3 = new ZipCode("00003", Arrays.asList());
ZipCode zipCode4 = new ZipCode("00004", Arrays.asList());
ZipCode zipCode5 = new ZipCode("00005", Arrays.asList(r3));
Person[] people = {
new Person(zipCode1),
new Person(zipCode2),
new Person(zipCode5)
};
Map<Person, List<Region>> result = Stream.of(people)
.collect(Collectors.toMap(person -> person,
person -> person.getZip().getRegions()));
result.entrySet().forEach(entry -> System.out.printf("[%s]: {%s}\n", entry.getKey(), entry.getValue()));
// Output:
// [Person: 0]: {[name: Region 1, name: Region 3]}
// [Person: 1]: {[name: Region 1, name: Region 2, name: Region 3]}
// [Person: 2]: {[name: Region 3]}
}
答案 4 :(得分:0)
其他一些答案包含对列表进行大量线性搜索的代码。我认为Java 8 Stream解决方案不应该比经典变体慢得多。 所以这是一个利用Streams而不会牺牲很多性能的解决方案。
List<Person> people = ...
List<Region> regions = ...
Map<String, List<Region>> zipToRegions =
regions.stream().collect(
() -> new HashMap<>(),
(map, region) -> {
for(String zipCode: region.getZipCodes()) {
List<Region> list = map.get(zipCode);
if(list == null) list = new ArrayList<>();
list.add(region);
map.put(zipCode, list);
}
},
(m1, m2) -> m1.putAll(m2)
);
Map<Person, List<Region>> personToRegions =
people.stream().collect(
Collectors.toMap(person -> person,
person -> zipToRegions.get(person.getZip()))
);