Java 8 Stream与地图和倍数集
作者:互联网
我正在尝试使用java8流编写以下行:
for (Town town : getAllTowns(routes)) {
if (originTown.equals(town))
continue;
for (Route route : routes) {
if (route.hasOrigin(originTown) && route.hasDestine(town)) {
distances.put(town, route.getDistance());
break;
}
distances.put(town, maxDistance);
}
}
return distances; //Map<Town,Integer>
到目前为止,我得到的结果是:
Map<Town, Integer> distances = getAllTowns(routes).stream()
.filter(town -> !originTown.equals(town))
.forEach(town -> routes.stream()
.filter(route -> route.hasOrigin(originTown) && route.hasDestine(town)
...)
return distances;
我该如何收集内部过滤器并构建Map<整数镇整数在哪里是route.getDistance()?
我尝试使用:
.collect(Collectors.toMap(route -> route.getDestineTown(), route -> route.getDistance()))
但是它在forEach调用内部,所以我无法将其返回到可变距离,因为它仅为内部调用生成地图.我不明白.任何输入都会真正有帮助.谢谢.
解决方法:
您可以使用findFirst()构建一个列表,其中包含每个城镇的第一条以该城镇为目的地的路线,然后在其上调用toMap().缺少城市的默认值可以单独处理.
Collection<Town> towns = getAllTowns(routes);
Map<Town, Integer> distances = towns.stream()
.filter(town -> !originTown.equals(town))
.map(town -> routes.stream()
.filter(route -> route.hasOrigin(originTown) && route.hasDestine(town))
.findFirst())
.filter(Optional::isPresent)
.collect(toMap(route -> route.get().getDestine(), route -> route.get().getDistance()));
towns.stream()
.filter(town -> !distances.containsKey(town))
.forEach(town -> distances.put(town, maxDistance));
(请注意,collect()中不再提供城镇,但是您可以利用以下事实:只有在目标城镇为城镇的情况下,才会添加每条路线.)
还要注意,toMap()不接受重复的键.如果到任何城镇都有多条路线(我认为可能有),则应改用groupingBy().
标签:java-8,java-stream,hashmap,foreach,java 来源: https://codeday.me/bug/20191118/2026903.html