This is a library of laconic method-aliases for safety stream operations with collections in Java.
Java 8+ introduces Stream API & Optional classes, but sometimes the syntax is really verbose even for simple stream manipulations. This library introduces method-aliases for some popular operation with collections.
For example, instead of the following code that maps users to modifiable list:
if (users != null) {
return users.stream().map(User::getFirstName).collect(Collectors.toList());
}
return new ArrayList<>();
you can use short static method from the Lists
class:
return map(users, User::getFirstName);
Min Requirements: JDK 8+
You can pull releases from the Maven Central repository: https://search.maven.org/artifact/io.github.avegera/stream-utils
Use the following dependency for Maven/Gradle:
- Maven
-
<dependency> <groupId>io.github.avegera</groupId> <artifactId>stream-utils</artifactId> <version>0.3.0</version> </dependency>
- Gradle
-
implementation 'io.github.avegera:stream-utils:0.3.0'
-
User Guide - TBD
Streams
contains NPE-safety methods for stream instantiating by provided input data. For example, the following method returns stream of users (or empty stream in case when users == null
):
Stream<User> stream = safeStream(users);
Lists
contains NPE-safety method-aliases for common Stream API intermediate operations like:
-
map()
-
filter()
-
flatMap()
-
distinct()
-
sort()
By default, the result of operations is a List
. Use suffix …ToSet()
in method name to return Set
instead. For example, the following method returns list of groups:
List<Group> groups = map(users, User::getGroup);
But this one returns set of groups:
Set<Group> groups = mapToSet(users, User::getGroup);
Aliases for terminal operations also available:
-
collect(toList())
-
collect(toSet())
-
count()
-
findFirst()
-
findAny()
-
allMatch()
-
anyMatch()
-
noneMatch()
For example, the following method returns first user from list or null if no users inside:
User user = findFirstOrNull(users);
This project is published under the Apache License 2.0, see http://www.apache.org/licenses/LICENSE-2.0 for details.