Jacki Jacki - 7 months ago 14
Java Question

Returning boolean value of comparing two lists

I found the following example that prints the similarities between two lists. In fact I only want to return

true
if both lists have the same values or
false
otherwise. For example, the following code should return return false.

public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
List<Integer> list2 = Arrays.asList(1, 2);

Set<Integer> similar = new HashSet<Integer>(list1);
similar.retainAll(list2);
System.out.println("Similar " + similar);
}

Answer

You should use List.equals:

public class HelloWorld{

     public static void main(String[] args) {
    List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
    List<Integer> list2 = Arrays.asList(1, 2);
    boolean test = list1.equals(list2);
    System.out.println("Similar  " + test);
}
}

So, equals from List will check if two lists are equal by full terms, same size and same values in it and on the same position. What you did with HashSet will only check if one list is subset of other list. However, if list1 is subset of list2 and list2 is subset of list1, they are equal (by math). But, List.equals() is faster and you need less memory then creating two Sets and do subset operations.

However, {1,2,3} is equal to {1,2,3} but not to {1,3,2} in terms of List.equals. If you want to {1,2,3} be equal to {1,3,2} and to {1,3,2,1,3} then you do it with Sets:

public class HelloWorld{

     public static void main(String[] args) {
    List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
    List<Integer> list2 = Arrays.asList(1, 2);

    Set<Integer> similar2 = new HashSet<Integer>(list2);
    Set<Integer> similar1 = new HashSet<Integer>(list1);
    boolean test = similar1.equals(similar2);
    System.out.println("Similar  " + test);
}
}

Set.equals works different then List.equals, since it checks if every element in similar1 exists in similar2 (by iteration), it doesn't care about the order. (Thank you @brso05 for pointing this out).