Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate the difference between two ArrayLists?

Tags:

java

arraylist

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 ?

like image 753
naveen Avatar asked May 28 '09 06:05

naveen


People also ask

Can you combine ArrayLists?

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 set two ArrayLists equal to each other?

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().


2 Answers

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] 
like image 106
William Brendel Avatar answered Sep 25 '22 16:09

William Brendel


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.

like image 24
andrii Avatar answered Sep 24 '22 16:09

andrii