I have two lists of arrays.
How do I easily compare equality of these with Java 8 and its features, without using external libraries? I am looking for a "better" (higher-level, shorter, more efficient) solution than brute-force code like this (untested code, may contain typos etc, not the point of the question):
boolean compare(List<String[]> list1, List<String[]> list2)
{
// tests for nulls etc omitted
if(list1.size() != list2.size()) {
return false;
}
for(i=0; i<list1.size(); ++i) {
if(!Arrays.equals(list1.get(i), list2.get(i))) {
return false;
}
}
return true;
}
Or, if there isn't any nicer way, that's a valid answer too.
Bonus: If Java 9 offers an even better way what whaterver Java 8 can offer, feel free to mention it as well.
Edit: After looking at the comments, and seeing how this question has become moderately hot, I think the "better" should include first checking lengths of all arrays, before checking array contents, because that has potential to find inequality much quicker, if inner arrays are long.
1) Solution based on Java 8 streams:
2) Much simpler solution (works in Java 5+):
3) Regarding your new requirement (to check the contained String arrays length first), you could write a generic helper method that does equality check for transformed lists:
Then the solution could be:
You could use a stream if the lists are random access lists (so that a call to
get
is fast - generally constant time) leading to:However, you might give as parameters some implementations that are not (such as LinkedLists). In this case, the best way is to use the iterator explicitly. Something like:
The
for
loop at least can be streamified, leading to:You could stream over one list and compare to each element of the other by using an iterator:
Using an iterator instead of the
get(index)
method on the first list is better because it doesn't matter whether the list isRandomAccess
or not.Note: this only works with a sequential stream. Using a parallel stream will lead to wrong results.
EDIT: As per the question last edit, which indicates it would be better to check the length of every pair of arrays in advance, I think it could be achieved with a slight modification to my previous code:
Here I'm using two iterators and am streaming
list2
twice, but I see no other way to check all lengths before checking the contents of the first pair of arrays. Check for lengths is null-safe, while check for contents is delegated to theArrays.equals(array1, array2)
method.using
zip
(which originates from lambda b93) function from https://stackoverflow.com/a/23529010/755183, code could look like:update
in order to check size of arrays first and then content this could be a solution to consider