Simple Way to Find If Two Different Lists Contain Exactly the Same Elements

Simple way to find if two different lists contain exactly the same elements?

If you care about order, then just use the equals method:

list1.equals(list2)

From the javadoc:

Compares the specified object with
this list for equality. Returns true
if and only if the specified object is
also a list, both lists have the same
size, and all corresponding pairs of
elements in the two lists are equal.
(Two elements e1 and e2 are equal if
(e1==null ? e2==null :
e1.equals(e2)).) In other words, two
lists are defined to be equal if they
contain the same elements in the same
order. This definition ensures that
the equals method works properly
across different implementations of
the List interface.

If you want to check independent of order, you could copy all of the elements to Sets and use equals on the resulting Sets:

public static <T> boolean listEqualsIgnoreOrder(List<T> list1, List<T> list2) {
return new HashSet<>(list1).equals(new HashSet<>(list2));
}

A limitation of this approach is that it not only ignores order, but also frequency of duplicate elements. For example, if list1 was ["A", "B", "A"] and list2 was ["A", "B", "B"] the Set approach would consider them to be equal.

If you need to be insensitive to order but sensitive to the frequency of duplicates you can either:

  • sort both lists (or copies) before comparing them, as done in this answer to another question
  • or copy all elements to a Multiset

Determine if 2 lists have the same elements, regardless of order?

You can simply check whether the multisets with the elements of x and y are equal:

import collections
collections.Counter(x) == collections.Counter(y)

This requires the elements to be hashable; runtime will be in O(n), where n is the size of the lists.

If the elements are also unique, you can also convert to sets (same asymptotic runtime, may be a little bit faster in practice):

set(x) == set(y)

If the elements are not hashable, but sortable, another alternative (runtime in O(n log n)) is

sorted(x) == sorted(y)

If the elements are neither hashable nor sortable you can use the following helper function. Note that it will be quite slow (O(n²)) and should generally not be used outside of the esoteric case of unhashable and unsortable elements.

def equal_ignore_order(a, b):
""" Use only when elements are neither hashable nor sortable! """
unmatched = list(b)
for element in a:
try:
unmatched.remove(element)
except ValueError:
return False
return not unmatched

Comparing if two lists have the same elements based on a property

You can check listA's all element exists in listB

boolean isSame = listA.stream()
.allMatch(a -> listB.stream()
.anyMatch(b -> b.getCode().equals(a.getCode())));

You can create a set of code from a list and check contains in O(1)

Set<String> set = listB.stream().map(e -> e.getCode()).collect(Collectors.toSet());

Then you can find in set for every list element

boolean isSame = listA.stream().allMatch(a -> set.contains(a.getCode()));

Two Arraylists have the same elements but in different order, are they equal?

if (INITIAL1.size() == PL1.size() && INITIAL1.containsAll(PL1)) {
//do something
}

Java ArrayList - how can I tell if two lists are equal, order not mattering?

You could sort both lists using Collections.sort() and then use the equals method. A slighly better solution is to first check if they are the same length before ordering, if they are not, then they are not equal, then sort, then use equals. For example if you had two lists of Strings it would be something like:

public  boolean equalLists(List<String> one, List<String> two){     
if (one == null && two == null){
return true;
}

if((one == null && two != null)
|| one != null && two == null
|| one.size() != two.size()){
return false;
}

//to avoid messing the order of the lists we will use a copy
//as noted in comments by A. R. S.
one = new ArrayList<String>(one);
two = new ArrayList<String>(two);

Collections.sort(one);
Collections.sort(two);
return one.equals(two);
}

Simple way to find if two different lists contain exactly the same elements?

If you care about order, then just use the equals method:

list1.equals(list2)

From the javadoc:

Compares the specified object with
this list for equality. Returns true
if and only if the specified object is
also a list, both lists have the same
size, and all corresponding pairs of
elements in the two lists are equal.
(Two elements e1 and e2 are equal if
(e1==null ? e2==null :
e1.equals(e2)).) In other words, two
lists are defined to be equal if they
contain the same elements in the same
order. This definition ensures that
the equals method works properly
across different implementations of
the List interface.

If you want to check independent of order, you could copy all of the elements to Sets and use equals on the resulting Sets:

public static <T> boolean listEqualsIgnoreOrder(List<T> list1, List<T> list2) {
return new HashSet<>(list1).equals(new HashSet<>(list2));
}

A limitation of this approach is that it not only ignores order, but also frequency of duplicate elements. For example, if list1 was ["A", "B", "A"] and list2 was ["A", "B", "B"] the Set approach would consider them to be equal.

If you need to be insensitive to order but sensitive to the frequency of duplicates you can either:

  • sort both lists (or copies) before comparing them, as done in this answer to another question
  • or copy all elements to a Multiset


Related Topics



Leave a reply



Submit