在使用流合并两个数组后,我只想保留它们的唯一值。这不是我正在寻找的 distinct()
函数:
int[] a = { 1, 2, 3 };
int[] b = { 3, 4, 5 };
int[] c = IntStream.concat(Arrays.stream(a), Arrays.stream(b)).distinct().toArray();
给我 c = {1, 2, 3, 4, 5}
,但我需要 c
为 {1, 2, 4, 5 }
有没有一种使用流来实现此目的的简单快捷的方法?
最佳答案
你可以这样做:
int[] a = { 1, 2, 3 };
int[] b = { 3, 4, 5 };
int[] c = IntStream.concat(Arrays.stream(a), Arrays.stream(b))
.boxed()
.collect(Collectors.collectingAndThen(
Collectors.groupingBy(Function.identity(), Collectors.counting()), // Freq map
m -> m.entrySet().stream()
.filter(e -> e.getValue() == 1) // Filter duplicates
.mapToInt(e -> e.getKey())
.toArray()
));
这首先为所有元素创建一个频率图,然后过滤掉出现不止一次的元素。
关于java - 使用 Java 8 流仅保留跨多个数组唯一的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39562821/