2 回答
TA贡献1966条经验 获得超4个赞
好吧,您可以构建一个Map<String, Map<String, List<String>>>,其中 key 是Neighborhood::id并且 value 是 a Map,其中 key 和 value 是Street::idList House::id。从这里将它重新构建回你想要的任何东西都留给你一个练习......
Map<String, Map<String, List<String>>> map = new HashMap<>();
neighborhoods.forEach(neighborhood -> {
Map<String, List<String>> m = map.computeIfAbsent(neighborhood.getId(), (key) -> new HashMap<>());
neighborhood.getStreets()
.forEach(street -> {
m.merge(street.getId(),
street.getHouses()
.stream()
.map(House::getId)
.collect(Collectors.toCollection(ArrayList::new)),
(oldV, newV) -> {
oldV.addAll(newV);
return oldV;
}
);
});
});
TA贡献1801条经验 获得超8个赞
我不得不稍微更改您提供的代码:
import java.util.List;
public class Neighborhood {
public String id;
public List<Street> streets;
public Neighborhood(String id, List<Street> streets) {
this.id = id;
this.streets = streets;
}
}
class Street {
public Street(String id, List<House> houses) {
this.id = id;
this.houses = houses;
}
public String id;
public List<House> houses;
}
class House {
public String id;
public House(String id) {
this.id = id;
}
}
这是我的答案:
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
House h1 = new House("h11");
Street s1 = new Street("s11", Arrays.asList(h1));
House h2 = new House("h12");
Street s2 = new Street("s11", Arrays.asList(h2));
Neighborhood n1 = new Neighborhood("n11", Arrays.asList(s1));
Neighborhood n2 = new Neighborhood("n11", Arrays.asList(s2));
Set<Street> collect = Stream.of(n1, n2).flatMap(neighborhood -> neighborhood.streets.stream())
.collect(Collectors.toSet());
System.out.println(collect);
final Map<String, List<Street>> collect1 = collect.stream().collect(Collectors.groupingBy(street -> street.id));
final List<Neighborhood> neighborhoods = new ArrayList<>();
collect1.forEach((s, streets) -> {
final List<House> collect2 = streets.stream().flatMap(street -> street.houses.stream())
.collect(Collectors.toList());
final Street street = new Street(s, collect2);
neighborhoods.add(new Neighborhood(s, Arrays.asList(street)));
});
}
}
添加回答
举报