gpt4 book ai didi

java - 使用 Java 8 流仅保留跨多个数组唯一的值

转载 作者:行者123 更新时间:2023-11-29 08:41:53 25 4
gpt4 key购买 nike

在使用流合并两个数组后,我只想保留它们的唯一值。这不是我正在寻找的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com