为了账号安全,请及时绑定邮箱和手机立即绑定

Java中ArrayList的交并

Java中ArrayList的交并

回首忆惘然 2019-07-02 10:34:01
Java中ArrayList的交并是否有办法这样做?我在找,但找不到。另一个问题:我需要这些方法来过滤文件。有些是AND过滤器和一些是OR过滤器(就像集合论中的那样),所以我需要根据所有文件和保存这些文件的UnitedArrayList/Intersects ArrayList进行过滤。我应该使用不同的数据结构来保存文件吗?还有什么能提供更好的运行时的吗?
查看完整描述

3 回答

?
MM们

TA贡献1886条经验 获得超2个赞

这里是一个没有使用任何第三方库的简单实现。主要优势retainAllremoveAlladdAll这些方法不修改输入到方法的原始列表。

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


查看完整回答
反对 回复 2019-07-02
?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

收藏(ArrayList也是如此)有:

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

如果接受重复,则使用列表实现;如果不接受重复,则使用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]


查看完整回答
反对 回复 2019-07-02
?
达令说

TA贡献1821条经验 获得超6个赞

这篇文章相当古老,但它是谷歌在寻找这个话题时第一次出现。

我想使用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());

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


查看完整回答
反对 回复 2019-07-02
  • 3 回答
  • 0 关注
  • 691 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信