Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersection and union of ArrayLists in Java

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 filters and some are OR filters (like in set theory), so I need to filter according to all files and the unite/intersects ArrayLists that holds those files.

Should I use a different data structure to hold the files? Is there anything else that would offer a better runtime?

like image 745
yotamoo Avatar asked Mar 12 '11 14:03

yotamoo


People also ask

How do you combine ArrayLists in Java?

Approach: ArrayLists can be joined in Java with the help of Collection. addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.

Can you compare two ArrayLists in Java?

You can compare two array lists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false.

How do you find the union and intersection of two arrays in Java?

Create two sets called union and intersection. To find the union, add the first array's elements to the set union. Now, add all the second array elements if they are not present in the set union. To find the intersection, find the common elements and add them to the set.

How do you find the intersection of a list in Java?

Intersection of Two Lists of StringsList<String> list = Arrays. asList("red", "blue", "blue", "green", "red"); List<String> otherList = Arrays. asList("red", "green", "green", "yellow");


1 Answers

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<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;     } } 
like image 167
adarshr Avatar answered Oct 03 '22 02:10

adarshr