Skip to content

The library of laconic method-aliases for safety stream operations with collections in Java

Notifications You must be signed in to change notification settings

avegera/stream-utils

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

30 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Laconic Stream Utils

This is a library of laconic method-aliases for safety stream operations with collections in Java.

Introduction

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);

Installation

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'

Streams

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

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);

License

This project is published under the Apache License 2.0, see http://www.apache.org/licenses/LICENSE-2.0 for details.

About

The library of laconic method-aliases for safety stream operations with collections in Java

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages