I have 2 arraylists of string object.
List<String> sourceList = new ArrayList<String>();
List<String> destinationList = new ArrayList<String>();
I have some logic where i need to process the source list and will end up with the destination list. The destination list will have some additional elements added to the source list or removed from source list.
My expected output is 2 ArrayList of string where the first list should have all the strings removed from the source and second list should have all the strings newly added to the source.
Any simpler method to achieve this?
The ArrayList. equals() is the method used for comparing two Array List. It compares the Array lists as, both Array lists should have the same size, and all corresponding pairs of elements in the two Array lists are equal. Parameters: This function has a single parameter which is an object to be compared for equality.
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.
Convert Lists to Collection
and use removeAll
Collection<String> listOne = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g"));
Collection<String> listTwo = new ArrayList(Arrays.asList("a","b", "d", "e", "f", "gg", "h"));
List<String> sourceList = new ArrayList<String>(listOne);
List<String> destinationList = new ArrayList<String>(listTwo);
sourceList.removeAll( listTwo );
destinationList.removeAll( listOne );
System.out.println( sourceList );
System.out.println( destinationList );
Output:
[c, g]
[gg, h]
[EDIT]
other way (more clear)
Collection<String> list = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g"));
List<String> sourceList = new ArrayList<String>(list);
List<String> destinationList = new ArrayList<String>(list);
list.add("boo");
list.remove("b");
sourceList.removeAll( list );
list.removeAll( destinationList );
System.out.println( sourceList );
System.out.println( list );
Output:
[b]
[boo]
This should check if two lists are equal, it does some basic checks first (i.e. nulls and lengths), then sorts and uses the collections.equals method to check if they are equal.
public boolean equalLists(List<String> a, List<String> b){
// Check for sizes and nulls
if (a == null && b == null) return true;
if ((a == null && b!= null) || (a != null && b== null) || (a.size() != b.size()))
{
return false;
}
// Sort and compare the two lists
Collections.sort(a);
Collections.sort(b);
return a.equals(b);
}
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