我只需要从集合中获取唯一值(集合中没有任何重复的值)。例如,此代码:
ArrayList<Integer> g = new ArrayList<>(Arrays.asList(1,1,2,2,3,4,5,5,5,6,6));
System.out.println(Arrays.toString(g.stream().mapToInt(Integer::intValue).distinct().toArray()));
给我这个结果:
[1, 2, 3, 4, 5, 6]
但是我想要结果:
[3, 4]
是否可以使用Stream API做到这一点?
List<Integer> source = Arrays.asList(1, 1, 2, 2, 3, 4, 5, 5, 5, 6, 6);
List<Integer> processed = source.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println(processed);