I have two ArrayLists.
ArrayList A contains:
['2009-05-18','2009-05-19','2009-05-21']
ArrayList B contains:
['2009-05-18','2009-05-18','2009-05-19','2009-05-19','2009-05-20','2009-05-21','2009-05-21','2009-05-22']
I have to compare ArrayList A and ArrayList B. The result ArrayList should contain the List which does not exist in ArrayList A.
ArrayList result should be:
['2009-05-20','2009-05-22']
how to compare ?
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.
Step 1: Declare the ArrayList 1 and add the values to it. Step 2: Create another ArrayList 2 with the same type. Step 3: Now, simply add the values from one ArrayList to another by using the method addAll().
In Java, you can use the Collection
interface's removeAll
method.
// Create a couple ArrayList objects and populate them // with some delicious fruits. Collection firstList = new ArrayList() {{ add("apple"); add("orange"); }}; Collection secondList = new ArrayList() {{ add("apple"); add("orange"); add("banana"); add("strawberry"); }}; // Show the "before" lists System.out.println("First List: " + firstList); System.out.println("Second List: " + secondList); // Remove all elements in firstList from secondList secondList.removeAll(firstList); // Show the "after" list System.out.println("Result: " + secondList);
The above code will produce the following output:
First List: [apple, orange] Second List: [apple, orange, banana, strawberry] Result: [banana, strawberry]
You already have the right answer. And if you want to make more complicated and interesting operations between Lists (collections) use apache commons collections (CollectionUtils) It allows you to make conjuction/disjunction, find intersection, check if one collection is a subset of another and other nice things.
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