A set of static utility methods to simplify filtering and querying Java's Collections.
A limited subset of .NET framework's LINQ Enumerable Methods for Java.
Filters a collection using the given predicate
List<T> filter(Collection<T> items, Predicate<T> predicate)
Returns the first element from a collection that matches the given predicate. Throws an exception if no matching element is found
T first(Collection<T> items, Predicate<T> predicate)
Returns the first element from a collection that matches the given predicate or null if no matching element is found
T firstOrNull(Collection<T> items, Predicate<T> predicate)
Returns true if any element of a collection matches the given predicate
boolean any(Collection<T> items, Predicate<T> predicate)
Returns true if all elements of a collection match the given predicate
boolean all(Collection<T> items, Predicate<T> predicate)
Returns true if the collection is null or contains no elements
boolean isEmpty(Collection items)
Returns the only element from a collection that matches the given predicate. Throws an exception if the number of found elements is not exactly 1
T single(Collection<T> items, Predicate<T> predicate)
Returns the only element from a collection that matches the given predicate or null if such element is not found. Throws an exception if there is more than 1 element matching the predicate
T singleOrNull(Collection<T> items, Predicate<T> predicate)
Returns the number of elements in a collection matching the given predicate
int count(Collection<T> items, Predicate<T> predicate)
Projects each element of a collection into a new collection
List<TResult> map(Collection<TSource> items, Mapper<TSource, TResult> mapper)
Add using Gradle:
compile 'com.github.simonpercic:collectionhelper:1.2.1'
// sample list
List<Integer> integerList = Arrays.asList(1, 4, 2, 7, 8, 0, 5);
// filter
List<Integer> largerThan2 = CollectionHelper.filter(integerList, new Predicate<Integer>() {
@Override public boolean apply(Integer intValue) {
return intValue > 2;
}
});
// map
List<String> mappedList = CollectionHelper.map(integerList, new Mapper<Integer, String>() {
@Override public String map(Integer intValue) {
return String.format("myString_%d", intValue);
}
});
Use the awesome Gradle Retrolambda Plugin with Java 8 to use lambdas:
// filter
List<Integer> largerThan2 = CollectionHelper.filter(integerList, intValue -> intValue > 2);
// map
List<String> mappedList = CollectionHelper.map(integerList, intValue -> String.format("myString_%d", intValue));
// or even using a method reference
List<String> simpleMappedList = CollectionHelper.map(integerList, String::valueOf);
If you are using Java 8 and are NOT on Android you can also use Streams to simplify working with Collections.
See CHANGELOG.md
Open source, distributed under the MIT License. See LICENSE for details.