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

标签 java arrays java-8 java-stream

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

相关文章:

java - 在 Java 8 上为 Maven 单元测试设置时区

java - 收到 SSLHandshakeException : Received fatal alert: handshake_failure from Payara server while trying to connect Third party URLs

java - 如何使用队列提供无限流?

java - 按字母顺序从 ArrayList 返回元素

java.sql.SQLException : ORA-01843: not a valid month when calling a procedure

Java将项目作为数组添加到类中

java - 全屏独占模式 JDesktopPane

php - 从 Laravel session 数组中删除项目

java - 循环java中的值之和

ios - UITableViewController 没有被 NSMutableArray 填充