diff --git a/lib/java-extras/src/main/java/org/triplea/java/collections/CollectionUtils.java b/lib/java-extras/src/main/java/org/triplea/java/collections/CollectionUtils.java index 345bac69be7..9966468593e 100644 --- a/lib/java-extras/src/main/java/org/triplea/java/collections/CollectionUtils.java +++ b/lib/java-extras/src/main/java/org/triplea/java/collections/CollectionUtils.java @@ -12,6 +12,7 @@ import java.util.Collection; import java.util.Comparator; import java.util.List; +import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import javax.annotation.Nullable; @@ -34,7 +35,7 @@ public static int countMatches(final Collection collection, final Predica checkNotNull(collection); checkNotNull(predicate); - return (int) ImmutableList.copyOf(collection).stream().filter(predicate).count(); + return (int) collection.stream().filter(predicate).count(); } /** @@ -49,7 +50,7 @@ public static List getMatches( checkNotNull(collection); checkNotNull(predicate); - return ImmutableList.copyOf(collection).stream().filter(predicate).collect(Collectors.toList()); + return collection.stream().filter(predicate).collect(Collectors.toList()); } /** @@ -68,22 +69,21 @@ public static List getNMatches( checkArgument(max >= 0, "max must not be negative"); checkNotNull(predicate); - return ImmutableList.copyOf(collection).stream() - .filter(predicate) - .limit(max) - .collect(Collectors.toList()); + return collection.stream().filter(predicate).limit(max).collect(Collectors.toList()); } /** return a such that a exists in c1 and a exists in c2. always returns a new collection. */ public static List intersection( final Collection collection1, final Collection collection2) { - if (collection1 == null || collection2 == null) { + if (collection1 == null + || collection2 == null + || collection1.isEmpty() + || collection2.isEmpty()) { return new ArrayList<>(); } - final Collection c1 = ImmutableSet.copyOf(collection1); - final Collection c2 = ImmutableSet.copyOf(collection2); - - return c1.stream().filter(c2::contains).collect(Collectors.toList()); + final Collection c2 = + (collection2 instanceof Set) ? collection2 : ImmutableSet.copyOf(collection2); + return collection1.stream().distinct().filter(c2::contains).collect(Collectors.toList()); } /** Returns a such that a exists in c1 but not in c2. Always returns a new collection. */ @@ -96,10 +96,9 @@ public static List difference( return new ArrayList<>(collection1); } - final Collection c1 = ImmutableSet.copyOf(collection1); - final Collection c2 = ImmutableSet.copyOf(collection2); - - return ImmutableList.copyOf(c1).stream().filter(not(c2::contains)).collect(Collectors.toList()); + final Collection c2 = + (collection2 instanceof Set) ? collection2 : ImmutableSet.copyOf(collection2); + return collection1.stream().distinct().filter(not(c2::contains)).collect(Collectors.toList()); } /**