prabu prabu - 1 year ago 109
Java Question

Simple way to compare 2 ArrayLists

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?

Answer Source

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 );


[c, g]
[gg, h]


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);


    sourceList.removeAll( list );
    list.removeAll( destinationList );

    System.out.println( sourceList );
    System.out.println( list );


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download