我有一个电台列表,每个电台都有一个 radio 列表。我需要创建电台到电台的查找 map 。我知道如何使用 Java 8 stream forEach 来做到这一点:
stationList.stream().forEach(station -> {
Iterator<Long> it = station.getRadioList().iterator();
while (it.hasNext()) {
radioToStationMap.put(it.next(), station);
}
});
但我相信应该有更简洁的方法,比如使用 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));
关于Java 8 将 List 转换为 Lookup Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43257795/