Java 8 将 List 转换为 Lookup Map
我有一个电台列表,每个电台都有一个收音机列表.我需要创建一个电台到电台的查找地图.我知道如何使用 Java 8 流 forEach 来做到这一点:
I have a list of Station, in each Station there is a list of radios. I need to create a lookup Map of radio to Station. I know how to use Java 8 stream forEach to do it:
stationList.stream().forEach(station -> {
Iterator<Long> it = station.getRadioList().iterator();
while (it.hasNext()) {
radioToStationMap.put(it.next(), station);
}
});
但我相信应该有更简洁的方式,比如使用 Collectors.mapping()
.
But I believe there should be more concise way like using Collectors.mapping()
.
有人可以帮忙吗?
推荐答案
这应该可以工作,你不需要第三方.
This should work and you don't need third parties.
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));
相关文章