Intersection and union of ArrayLists in Java

后端 未结 24 2532
离开以前
离开以前 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:49

    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 list1 = new ArrayList(Arrays.asList("A", "B", "C"));
            List list2 = new ArrayList(Arrays.asList("B", "C", "D", "E", "F"));
    
            System.out.println(new Test().intersection(list1, list2));
            System.out.println(new Test().union(list1, list2));
        }
    
        public  List union(List list1, List list2) {
            Set set = new HashSet();
    
            set.addAll(list1);
            set.addAll(list2);
    
            return new ArrayList(set);
        }
    
        public  List intersection(List list1, List list2) {
            List list = new ArrayList();
    
            for (T t : list1) {
                if(list2.contains(t)) {
                    list.add(t);
                }
            }
    
            return list;
        }
    }
    

提交回复
热议问题