问题

有没有办法这样做?我在寻找但却找不到任何东西。

另一个问题:我需要这些方法,所以我可以过滤文件。有些是AND过滤器,有些是OR过滤器(就像在集合论中一样),所以我需要根据所有文件进行过滤,并且需要使用包含这些文件的联合/交叉ArrayLists。

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


#1 热门回答(108 赞)

Collection(所以也是ArrayList)有:

col.retainAll(otherCol) // for intersection
col.addAll(otherCol) // for union

如果你接受重复,请使用List实现,如果不接受,则使用Set实现:

Collection<String> col1 = new ArrayList<String>(); // {a, b, c}
// Collection<String> col1 = new TreeSet<String>();
col1.add("a");
col1.add("b");
col1.add("c");

Collection<String> col2 = new ArrayList<String>(); // {b, c, d, e}
// Collection<String> col2 = new TreeSet<String>();
col2.add("b");
col2.add("c");
col2.add("d");
col2.add("e");

col1.addAll(col2);
System.out.println(col1); 
//output for ArrayList: [a, b, c, b, c, d, e]
//output for TreeSet: [a, b, c, d, e]

#2 热门回答(104 赞)

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

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;
    }
}

#3 热门回答(47 赞)

这篇文章相当陈旧,但它仍然是第一个在谷歌搜索该主题时出现的帖子。

我想使用Java 8流进行更新(基本上)在一行中执行相同的操作:

List<T> intersect = list1.stream()
    .filter(list2::contains)
    .collect(Collectors.toList());

List<T> union = Stream.concat(list1.stream(), list2.stream())
    .distinct()
    .collect(Collectors.toList());

如果有人有更好/更快的解决方案让我知道,但这个解决方案是一个很好的单线程,可以很容易地包含在方法中,而无需添加不必要的帮助程序类/方法,仍然保持可读性。


原文链接