
org.opentripplanner.framework.collection.CollectionUtils Maven / Gradle / Ivy
Show all versions of otp Show documentation
package org.opentripplanner.framework.collection;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
public class CollectionUtils {
/**
* A null-safe version of toString() for a collections.
*
* If the collection is {@code null} the given {@code nullText} is returned.
*
* All elements are also converted to a sting using the {@code toString()} method or if
* {@code null} to the given {@code nullText}.
*
* If the collection is a set, but not a SortedSet then the elements are sorted. This is done
* to return the elements in a deterministic manner, which is important if this is used in
* for example a unit-test.
*
* The final result string examples: {@code "[]", "[a]", "[a, b, c]"}
*/
public static String toString(@Nullable Collection c, String nullText) {
if (c == null) {
return nullText;
}
var stream = c.stream().map(it -> it == null ? nullText : it.toString());
if (c instanceof Set && !(c instanceof SortedSet)) {
stream = stream.sorted();
}
return stream.collect(Collectors.joining(", ", "[", "]"));
}
/**
* A null-safe version of isEmpty() for a collection.
*
* If the collection is {@code null} then {@code true} is returned.
*
* If the collection is empty then {@code true} is returned.
*
* Otherwise {@code false} is returned.
*/
public static boolean isEmpty(@Nullable Collection> c) {
return c == null || c.isEmpty();
}
/**
* Look up the given key in a Map, return null if the key is null.
* This prevents a NullPointerException if the underlying implementation of the map does not
* accept querying with null keys (e.g. ImmutableMap).
*
**/
@Nullable
public static V getByNullableKey(K key, Map map) {
if (key == null) {
return null;
}
return map.get(key);
}
}