请让我知道是否有可能根据Java 8使用并行流更改以下代码?使用流的HashMap操作Java 8
我正在寻找一个选项来并行运行“outer for loop”,并最终将所有的stationMap值一起收集起来?
Map<Integer, Set<Integer>> stationMap = new HashMap<>();
Map<Integer, Set<Integer>> routes = function();
for (Map.Entry<Integer, Set<Integer>> entry : routes.entrySet())
{
Set<Integer> stations = entry.getValue();
for (Integer station : stations) {
Set<Integer> temporaryStations = new HashSet<>(stations);
Set<Integer> stationSet = stationMap.get(station);
if (stationSet == null) {
stationSet = new HashSet<>();
temporaryStations.remove(station);
stationSet.addAll(temporaryStations);
stationMap.put(station, stationSet);
} else {
temporaryStations.remove(station);
stationSet.addAll(temporaryStations);
}
}
}
更短的版本:
routes.forEach((k, stations) -> {
stations.forEach((station) -> {
Set<Integer> stationSet = stationMap.get(station);
if (stationSet == null) {
stationSet = new HashSet<>();
stationSet.addAll(stations);
stationMap.put(station, stationSet);
} else {
stationSet.addAll(stations);
}
});
});
首先您可以查看您的代码并告诉我们您在做什么?我认为这可以简化。看起来有点不妥。答案是使用这样的事情,'routes.keySet() \t \t \t .parallelStream() \t \t \t .forEach(键 - > { \t \t \t \t决胜盘站= routes.get(关键); \t \t \t \t站 \t \t \t \t \t .parallelStream()\t \t \t \t \t \t \t \t \t \t \t \t .forEach(V - > stationMap.put(V,站));; \t \t \t});' –
非常感谢。但是stationMap.put(v,station)有一个小问题....我实际上试图添加以前的站,当我把站设置到stationMap(“stationSet.addAll(temporaryStations);”)时。现在的问题是它取代了现有的集合 – Dev
我试图得到以前的电台,并添加它,但它抛出并发修改异常:( – Dev