Java中ArrayLists的交集和联合

时间:2011-03-12 14:21:27

标签: java list union intersection

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

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

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

24 个答案:

答案 0 :(得分:113)

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]

答案 1 :(得分:113)

这是一个不使用任何第三方库的简单实现。与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;
    }
}

答案 2 :(得分:61)

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

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

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

答案 3 :(得分:32)

list1.retainAll(list2) - is intersection

union将是removeAll,然后是addAll

在集合文档中查找更多内容(ArrayList是一个集合) http://download.oracle.com/javase/1.5.0/docs/api/java/util/Collection.html

答案 4 :(得分:18)

仅为集合而非列表定义的联合和交叉点。如你所说。

检查guava库中的过滤器。番石榴也提供了真正的intersections and unions

 static <E> Sets.SetView<E >union(Set<? extends E> set1, Set<? extends E> set2)
 static <E> Sets.SetView<E> intersection(Set<E> set1, Set<?> set2)

答案 5 :(得分:10)

您可以使用apache commons中的CollectionUtils

答案 6 :(得分:8)

标记的解决方案效率不高。它具有O(n ^ 2)时间复杂度。我们可以做的是对两个列表进行排序,并执行下面的交叉算法。

private  static ArrayList<Integer> interesect(ArrayList<Integer> f, ArrayList<Integer> s) { 
    ArrayList<Integer> res = new ArrayList<Integer>();

    int i = 0, j = 0; 
    while (i != f.size() && j != s.size()) { 

        if (f.get(i) < s.get(j)) {
            i ++;
        } else if (f.get(i) > s.get(j)) { 
            j ++;
        } else { 
            res.add(f.get(i)); 
            i ++;  j ++;
        }
    }


    return res; 
}

这个复杂度为O(n log n + n),其为O(n log n)。 工会以类似的方式完成。只需确保在if-elseif-else语句中进行适当的修改。

如果你愿意,你也可以使用迭代器(我知道它们在C ++中效率更高,我不知道在Java中是否也是如此)。

答案 7 :(得分:4)

我认为你应该使用Set来保存文件,如果你想对它们进行交集和联合。然后,您可以使用GuavaSets课程来unionintersection并按Predicate进行过滤。这些方法与其他建议之间的区别在于,所有这些方法都会创建两个集合的并集,交集等的延迟视图。 Apache Commons创建一个新的集合并将数据复制到它。 retainAll通过从中删除元素来更改其中一个集合。

答案 8 :(得分:4)

这是一种如何与流进行交集的方法(记住你必须使用java 8进行流):

List<foo> fooList1 = new ArrayList<>(Arrays.asList(new foo(), new foo()));
List<foo> fooList2 = new ArrayList<>(Arrays.asList(new foo(), new foo()));
fooList1.stream().filter(f -> fooList2.contains(f)).collect(Collectors.toList());

具有不同类型的列表的示例。如果你在foo和bar之间有一个实现,你可以从foo获得一个bar-object,而不是修改你的流:

List<foo> fooList = new ArrayList<>(Arrays.asList(new foo(), new foo()));
List<bar> barList = new ArrayList<>(Arrays.asList(new bar(), new bar()));

fooList.stream().filter(f -> barList.contains(f.getBar()).collect(Collectors.toList());

答案 9 :(得分:3)

  • retainAll将修改您的列表
  • Guava没有List for List(仅适用于set)

我发现ListUtils对这个用例非常有用。

如果您不想修改现有列表,请使用org.apache.commons.collections中的ListUtils。

ListUtils.intersection(list1, list2)

答案 10 :(得分:2)

在Java 8中,我使用这样的简单帮助方法:

public static <T> Collection<T> getIntersection(Collection<T> coll1, Collection<T> coll2){
    return Stream.concat(coll1.stream(), coll2.stream())
            .filter(coll1::contains)
            .filter(coll2::contains)
            .collect(Collectors.toSet());
}

public static <T> Collection<T> getMinus(Collection<T> coll1, Collection<T> coll2){
    return coll1.stream().filter(not(coll2::contains)).collect(Collectors.toSet());
}

public static <T> Predicate<T> not(Predicate<T> t) {
    return t.negate();
}

答案 11 :(得分:1)

如果列表中的对象是可散列的(即具有合适的hashCode和等于函数),则表格之间的最快方法约为。尺寸&gt; 20是为两个列表中较大的一个构造一个HashSet。

public static <T> ArrayList<T> intersection(Collection<T> a, Collection<T> b) {
    if (b.size() > a.size()) {
        return intersection(b, a);
    } else {
        if (b.size() > 20 && !(a instanceof HashSet)) {
            a = new HashSet(a);
        }
        ArrayList<T> result = new ArrayList();
        for (T objb : b) {
            if (a.contains(objb)) {
                result.add(objb);
            }
        }
        return result;
    }
}

答案 12 :(得分:1)

Java 8以来的单一流水线

导入静态java.util.stream.Stream.concat;
导入静态java.util.stream.Collectors.toList;
导入静态java.util.stream.Collectors.toSet;

没有重复的联盟:

  return concat(a.stream(), b.stream()).collect(toList());

联盟与众不同:

  return concat(a.stream(), b.stream()).distinct().collect(toList());

联合,如果Collection / Set返回类型是不同的,则为独立的:

  return concat(a.stream(), b.stream()).collect(toSet());

如果没有重复则相交:

  return a.stream().filter(b::contains).collect(toList());

如果集合b很大而不是O(1),则通过在return之前添加1行来预先优化过滤器性能。复制到HasSet import java.util.Set;

... b = Set.copyOf(b);

相交且不同:

  return a.stream().distinct().filter(b::contains).collect(toList());

答案 13 :(得分:1)

我也在研究类似的情况,并到达这里寻求帮助。结束了为阵列找到我自己的解决方案。 ArrayList AbsentDates = new ArrayList(); //将存储Array1-Array2

注意:发布此内容,如果它可以帮助某人访问此页面以获取帮助。

ArrayList<String> AbsentDates = new ArrayList<String>();//This Array will store difference
      public void AbsentDays() {
            findDates("April", "2017");//Array one with dates in Month April 2017
            findPresentDays();//Array two carrying some dates which are subset of Dates in Month April 2017

            for (int i = 0; i < Dates.size(); i++) {

                for (int j = 0; j < PresentDates.size(); j++) {

                    if (Dates.get(i).equals(PresentDates.get(j))) {

                        Dates.remove(i);
                    }               

                }              
                AbsentDates = Dates;   
            }
            System.out.println(AbsentDates );
        }

答案 14 :(得分:1)

您可以使用commons-collections4 CollectionUtils

Collection<Integer> collection1 = Arrays.asList(1, 2, 4, 5, 7, 8);
Collection<Integer> collection2 = Arrays.asList(2, 3, 4, 6, 8);

Collection<Integer> intersection = CollectionUtils.intersection(collection1, collection2);
System.out.println(intersection); // [2, 4, 8]

Collection<Integer> union = CollectionUtils.union(collection1, collection2);
System.out.println(union); // [1, 2, 3, 4, 5, 6, 7, 8]

Collection<Integer> subtract = CollectionUtils.subtract(collection1, collection2);
System.out.println(subtract); // [1, 5, 7]

答案 15 :(得分:0)

您可以使用以下方法:

CollectionUtils.containsAnyCollectionUtils.containsAll

来自Apache Commons

答案 16 :(得分:0)

retainAll()方法用于查找公共元素。即交叉点 list1.retainAll(list2)

答案 17 :(得分:0)

public static <T> Set<T> intersectCollections(Collection<T> col1, Collection<T> col2) {
    Set<T> set1, set2;
    if (col1 instanceof Set) {
        set1 = (Set) col1;
    } else {
        set1 = new HashSet<>(col1);
    }

    if (col2 instanceof Set) {
        set2 = (Set) col2;
    } else {
        set2 = new HashSet<>(col2);
    }

    Set<T> intersection = new HashSet<>(Math.min(set1.size(), set2.size()));

    for (T t : set1) {
        if (set2.contains(t)) {
            intersection.add(t);
        }
    }

    return intersection;
}

答案 18 :(得分:0)

基于公用键-Java 8的两个不同对象的列表的交集

 private List<User> intersection(List<User> users, List<OtherUser> list) {

        return list.stream()
                .flatMap(OtherUser -> users.stream()
                        .filter(user -> user.getId()
                                .equalsIgnoreCase(OtherUser.getId())))
                .collect(Collectors.toList());
    }

答案 19 :(得分:0)

经过测试,这是我最好的交叉点方法。

与纯HashSet方法相比,速度更快。下面的HashSet和HashMap对于具有超过100万条记录的数组具有类似的性能。

对于Java 8 Stream方法,对于大于10k的数组,速度非常慢。

希望这会有所帮助。

public static List<String> hashMapIntersection(List<String> target, List<String> support) {
    List<String> r = new ArrayList<String>();
    Map<String, Integer> map = new HashMap<String, Integer>();
    for (String s : support) {
        map.put(s, 0);
    }
    for (String s : target) {
        if (map.containsKey(s)) {
            r.add(s);
        }
    }
    return r;
}
public static List<String> hashSetIntersection(List<String> a, List<String> b) {
    Long start = System.currentTimeMillis();

    List<String> r = new ArrayList<String>();
    Set<String> set = new HashSet<String>(b);

    for (String s : a) {
        if (set.contains(s)) {
            r.add(s);
        }
    }
    print("intersection:" + r.size() + "-" + String.valueOf(System.currentTimeMillis() - start));
    return r;
}

public static void union(List<String> a, List<String> b) {
    Long start = System.currentTimeMillis();
    Set<String> r= new HashSet<String>(a);
    r.addAll(b);
    print("union:" + r.size() + "-" + String.valueOf(System.currentTimeMillis() - start));
}

答案 20 :(得分:0)

首先,我将数组的所有值复制到一个数组中然后我将重复值删除到数组中。第12行,解释相同的数字是否超过时间然后将一些额外的垃圾值放入&#34; j&#34;位置。最后,从起始端遍历并检查是否发生相同的垃圾值然后丢弃。

public class Union {
public static void main(String[] args){

    int arr1[]={1,3,3,2,4,2,3,3,5,2,1,99};
    int arr2[]={1,3,2,1,3,2,4,6,3,4};
    int arr3[]=new int[arr1.length+arr2.length];

    for(int i=0;i<arr1.length;i++)
        arr3[i]=arr1[i];

    for(int i=0;i<arr2.length;i++)
        arr3[arr1.length+i]=arr2[i];
    System.out.println(Arrays.toString(arr3));

    for(int i=0;i<arr3.length;i++)
    {
        for(int j=i+1;j<arr3.length;j++)
        {
            if(arr3[i]==arr3[j])
                arr3[j]=99999999;          //line  12
        }
    }
    for(int i=0;i<arr3.length;i++)
    {
        if(arr3[i]!=99999999)
            System.out.print(arr3[i]+" ");
    }
}   
}

答案 21 :(得分:0)

最终解决方案:

encoding="ISO-8859-2"

答案 22 :(得分:-1)

如果数字匹配而不是我检查它是否是第一次出现或未经过&#34; indexOf()&#34;如果该号码第一次匹配则打印并保存到一个字符串中,这样,当下一次相同的号码匹配时,它将不会打印,因为由于&#34; indexOf()&#34;条件是假的。

class Intersection
{
public static void main(String[] args)
 {
  String s="";
    int[] array1 = {1, 2, 5, 5, 8, 9, 7,2,3512451,4,4,5 ,10};
    int[] array2 = {1, 0, 6, 15, 6, 5,4, 1,7, 0,5,4,5,2,3,8,5,3512451};


       for (int i = 0; i < array1.length; i++)
       {
           for (int j = 0; j < array2.length; j++)
           {
               char c=(char)(array1[i]);
               if(array1[i] == (array2[j])&&s.indexOf(c)==-1)
               {    
                System.out.println("Common element is : "+(array1[i]));
                s+=c;
                }
           }
       }    
}

}

答案 23 :(得分:-1)

如果你的数据是集合,你可以使用Guava的Sets类。

相关问题