Java中ArrayLists的交集和联合 [英] Intersection and union of ArrayLists in Java

查看:112
本文介绍了Java中ArrayLists的交集和联合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有方法可以这样做?我正在寻找但找不到任何。

Are there any methods to do so? I was looking but couldn't find any.

另一个问题:我需要这些方法,所以我可以过滤文件。
有些是 AND 过滤器,有些是 OR 过滤器(比如集合论),所以我需要根据所有文件过滤和unite / intersects保存这些文件的ArrayLists。

Another question: I need these methods so I can filter files. Some are AND filters and some are OR filters (like in set theory), so I need to filter according to all files and the unite/intersects ArrayLists that holds those files.

我应该使用不同的数据结构来保存文件吗?还有什么能提供更好的运行时间吗?

Should I use a different data structure to hold the files? Is there anything else that would offer a better runtime?

推荐答案

这是一个不使用任何第三方库的简单实现。主要优势超过 retainAll removeAll addAll 就是这些方法不会修改输入到方法的原始列表。

Here's a plain implementation without using any third-party library. Main advantage over retainAll, removeAll and addAll is that these methods don't modify the original lists input to the methods.

public class Test {

    public static void main(String... args) throws Exception {

        List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C"));
        List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F"));

        System.out.println(new Test().intersection(list1, list2));
        System.out.println(new Test().union(list1, list2));
    }

    public <T> List<T> union(List<T> list1, List<T> list2) {
        Set<T> set = new HashSet<T>();

        set.addAll(list1);
        set.addAll(list2);

        return new ArrayList<T>(set);
    }

    public <T> List<T> intersection(List<T> list1, List<T> list2) {
        List<T> list = new ArrayList<T>();

        for (T t : list1) {
            if(list2.contains(t)) {
                list.add(t);
            }
        }

        return list;
    }
}

这篇关于Java中ArrayLists的交集和联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆