Nic*_*ico 8 java lookup java-8 java-stream collectors
我有一个电台列表,在每个电台中都有一个收音机列表。我需要创建电台到电台的查找地图。我知道如何使用Java 8流forEach来做到这一点:
stationList.stream().forEach(station -> {
Iterator<Long> it = station.getRadioList().iterator();
while (it.hasNext()) {
radioToStationMap.put(it.next(), station);
}
});
Run Code Online (Sandbox Code Playgroud)
但是我相信应该有更简洁的使用方式Collectors.mapping()。
有人可以帮忙吗?
这应该可行,并且不需要第三方。
stationList.stream()
.map(s -> s.getRadioList().stream().collect(Collectors.toMap(b -> b, b -> s)))
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
Run Code Online (Sandbox Code Playgroud)
与混合解决方案相比,我认为您无法使用收集器以更简洁的方式做到这一点
stationList.stream().forEach(station -> {
for ( Long radio : station.getRadioList() ) {
radioToStationMap.put(radio, station);
}
});
Run Code Online (Sandbox Code Playgroud)
或者
stationList.forEach(station -> {
station.getRadioList().forEach(radio -> {
radioToStationMap.put(radio, station);
});
});
Run Code Online (Sandbox Code Playgroud)
(可以直接在集合上调用 .forEach ,不需要经过.stream())
我能想出的最短的完全“功能”解决方案是这样的
stationList.stream().flatMap(
station -> station.getRadioList().stream().map(radio -> new Pair<>(radio, station)))
.collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
Run Code Online (Sandbox Code Playgroud)
使用第三方库中提供的任何 Pair 类。与 Xtend 或 Groovy 等方言相比,Java 8 对于简单操作来说非常冗长。