software.amazon.awssdk.testutils.UnorderedCollectionComparator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of test-utils Show documentation
Show all versions of test-utils Show documentation
The AWS SDK for Java - Test Utils module holds the all the utilities that are used by the tests.
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package software.amazon.awssdk.testutils;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* This class includes some utility methods for comparing two unordered
* collections.
*/
public final class UnorderedCollectionComparator {
private UnorderedCollectionComparator() {
}
/**
* Compares two unordered lists of the same type.
*/
public static boolean equalUnorderedCollections(
Collection colA, Collection colB) {
return equalUnorderedCollections(colA, colB, (a, b) -> (a == b) || a != null && a.equals(b));
}
/**
* Compares two unordered lists of different types, using the specified
* cross-type comparator. Null collections are treated as empty ones.
* Naively implemented using N(n^2) algorithm.
*/
public static boolean equalUnorderedCollections(
Collection colA, Collection colB,
final CrossTypeComparator comparator) {
if (colA == null || colB == null) {
if ((colA == null || colA.isEmpty())
&& (colB == null || colB.isEmpty())) {
return true;
} else {
return false;
}
}
// Add all elements into sets to remove duplicates.
Set setA = new HashSet<>(colA);
Set setB = new HashSet<>(colB);
if (setA.size() != setB.size()) {
return false;
}
for (A a : setA) {
boolean foundA = false;
for (B b : setB) {
if (comparator.equals(a, b)) {
foundA = true;
break;
}
}
if (!foundA) {
return false;
}
}
return true;
}
/**
* A simple interface that attempts to compare objects of two different types
*/
public interface CrossTypeComparator {
/**
* @return True if a and b should be treated as equal.
*/
boolean equals(A a, B b);
}
}