Compare List Java

For immutableuse equallist we simple use list.equal list it return true if content same. (compare index)

 //case true 

List<Integer> listOne = new ArrayList<>(Arrays.asList(1, 4, 6, 3, 66, 3, 33));
List<Integer> listTwo = new ArrayList<>(Arrays.asList(1, 4, 6, 3, 66, 3, 33));
System.out.println("WrapperClass listOne.equals(listTwo): " + listOne.equals(listTwo));

 

// case false
List<Integer> listOne = new ArrayList<>(Arrays.asList(1, 4, 6, 3, 66, 3, 33));
List<Integer> listTwo = new ArrayList<>(Arrays.asList(4, 1, 6, 3, 66, 3, 33));
System.out.println("WrapperClass listOne.equals(listTwo): " + listOne.equals(listTwo));

 

We can compare list withlist by various ways:


Operator ==: true if two list similar memory (oparator =) example below.
List a = list b
return a == b return true

Equal Method (compare index): True if element is immutable class, if class is customize(self definition). we must override Equal & hascode method of class element, if not return false all case.

removeAllmethod then check size: It method dependent method equal check delete so we must override Equal & hashcode method of class element. (not distinguish index). Notice must copy list original by new ArrayList<>(listoriginal) before compare if not list original will be remove some element.

retainAllmethodthen compare size: It method dependent method equal  check delete defference so we must override Equal & hashcode method of class element.
(not distinguish index) . Notice must copy list original by new ArrayList<>(listoriginal) before compare if not list original will be remove some elements.

 
Stream filterListCheckContain Collect: Use predicate of inside method fillter of Stream. it indepent of method equal & hashcode of class element so we must override them.
(not distinguish index)

 

Github: https://github.com/nguyenthinhit996/sharefullcode/blob/master/Learn%20Java/Java%20Basic/ListCollection/src/collectionsinJava/listinterface/comparelist/CompareToArrayLists.java

 

0 comments :

Post a Comment

Cancel Reply

About Me

My photo
Tân An, Long An, Vietnam
Hello everyone, I love programming, I love making friends with people all over the world.