你映射Map.Entry
到Set<Long>
情况下,这意味着失去跟踪的原始地图的按键,这使得它不可能将其收集到具有相同密钥的新地图的实例。
第一个选项是向Map.Entry<Long, List<MyClass>>
实例映射到Map.Entry<Long, Set<Long>>
实例,然后收集的条目到一个新的图:
Map<Long, Set<Long>> result=
myFirstMap.entrySet().stream()
.map(e -> new AbstractMap.SimpleImmutableEntry<>(e.getKey(),
e.getValue().stream().map(MyClass::getId).collect(Collectors.toSet())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
另一种方法是熔化map
和collect
步骤为一体,做变换就在提供给toMap
收集值函数:
Map<Long, Set<Long>> result=
myFirstMap.entrySet().stream().collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().stream().map(MyClass::getId).collect(Collectors.toSet())));
这样,就避免了创建新Map.Entry
实例,并得到但是,更简洁的代码非常灵活,因为您无法链接其他流操作。
你的编辑无效的答案是已经在这里待了一年。请不要这样做。 – shmosel