Intersection and union of ArrayLists in Java

后端 未结 24 2590
离开以前
离开以前 2020-11-22 06:05

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

Another question: I need these methods so I can filter files. Some are AND filter

24条回答
  •  庸人自扰
    2020-11-22 06:55

    Final solution:

    //all sorted items from both
    public  List getListReunion(List list1, List list2) {
        Set set = new HashSet();
        set.addAll(list1);
        set.addAll(list2);
        return new ArrayList(set);
    }
    
    //common items from both
    public  List getListIntersection(List list1, List list2) {
        list1.retainAll(list2);
        return list1;
    }
    
    //common items from list1 not present in list2
    public  List getListDifference(List list1, List list2) {
        list1.removeAll(list2);
        return list1;
    }
    

提交回复
热议问题