【发布时间】:2018-05-14 13:22:04
【问题描述】:
我是 Java 8 的新手,我有以下转换要求:
Map<Shape, int[]> --> Map<Shape, Set<Integer>>
有什么想法吗?
【问题讨论】:
标签: java dictionary java-8 set
我是 Java 8 的新手,我有以下转换要求:
Map<Shape, int[]> --> Map<Shape, Set<Integer>>
有什么想法吗?
【问题讨论】:
标签: java dictionary java-8 set
我编辑了这个问题,希望Set<Integer> 是您真正需要的,因为您不能拥有Set<int> 类型的原始Set。
map.entrySet()
.stream()
.collect(Collectors.toMap(
Entry::getKey,
x -> Arrays.stream(x.getValue()).boxed().collect(Collectors.toSet())
));
另一方面,如果你真的想要独特的原语,那么 distinct 和 toArray 可以工作,但类型仍然是 Map<Shape, int[]>:
map.entrySet()
.stream()
.collect(Collectors.toMap(
Entry::getKey,
x -> Arrays.stream(x.getValue()).distinct().toArray()
));
【讨论】:
Set<int>,而只能获得Set<Integer>?
这是一种将int数组转换为Set<Integer>的方法:
private Set<Integer> convertArrayToSet(int[] array) {
return stream(array).boxed().collect(toSet());
}
你需要通过这个方法跳过map的每个值:
public Map<Shape, Set<Integer>> convert(Map<Shape, int[]> map) {
return map.entrySet()
.stream()
.collect(toMap(e -> e.getKey(), e -> convertArrayToSet(e.getValue())));
}
我使用了Arrays、Collectors 的静态导入来缩短 sn-ps。
【讨论】: