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?
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.
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.
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.
Intersection of Two Lists of StringsList<String> list = Arrays. asList("red", "blue", "blue", "green", "red"); List<String> otherList = Arrays. asList("red", "green", "green", "yellow");
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With