how to Identify is there any addittion or deletion or same Object in new nested list compared to old nested list

how to Identify is there any addittion or deletion or same Object in new nested list compared to old nested list



i have two lists as shown below.


List<Component> oldComps =getOldComps();
List<Component> newcomps=getNewComps();



corresponding POJOS are:


public class Component
private List<Endpoint> endpoints;


public class Endpoint
private String path;



i have a use case where i need to identify:



newComps



oldComps



for detailed exaple : as shown in attached images if oldComps and newComps
==>contains same data.






Give definition of same data. Are we talking of same objects - Endpoints - "==" , or are we talking with same data in the sense of equals ?

– Alexandar Petrov
Sep 13 '18 at 17:49







If you can implement equals and hashCode for Component class, and then using Collections utiltity or Guava collection to find out answers for your questions

– Nghia Do
Sep 13 '18 at 17:50




3 Answers
3



Based on the presumption you have hashcode correct.


HashSet oldComponentSet = new HashSet(oldComps);
HashSet newComponentSet = new HashSet(newComps);
//this line will give you intersection
oldComponentSet.retainAll(setTwo);
// this line will give you difference
newComponentSet.removeAll(oldComponentSet)
//united differfence based on presumption above two lines were not executed
oldComponentSet.removeAll(newComponentSet).add(newComponentSet.removeAll(oldComponentSet));






@FedericoPeraltaSchaffner my bad :) got too used to functional syntax. I will fix it now.

– Alexandar Petrov
Sep 13 '18 at 18:30



You can get the hash code of your data structure which is a built-in function on many modern programming language to compare with another one.



You can get the result by calling the hashCode() method from the object that you want. In your case, oldComps.hashCode() will give you the result.



For further: hashCode() by Baeldung



You can use .equals() method to compare the two lists.


.equals()



To find any component which is not in the other list you can use .removeAll() method of List class to identify the unique element.


.removeAll()


List



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.