Collector
public static <T> Collector<T, ?, T> toSingleton() {
return Collectors.collectingAndThen(
Collectors.toList(),
list -> {
if (list.size() != 1) {
throw new IllegalStateException();
}
return list.get(0);
}
);
}
We use Collectors.collectingAndThen
to construct our desired Collector
by
List
with the Collectors.toList()
collector.IllegalStateException
if list.size != 1
.Used as:
User resultUser = users.stream()
.filter(user -> user.getId() > 0)
.collect(toSingleton());
You can then customize this Collector
as much as you want, for example give the exception as argument in the constructor, tweak it to allow two values, and more.
You can use a 'workaround' that involves peek()
and an AtomicInteger
, but really you shouldn't be using that.
What you could do istead is just collecting it in a List
, like this:
LinkedList<User> users = new LinkedList<>();
users.add(new User(1, "User1"));
users.add(new User(2, "User2"));
users.add(new User(3, "User3"));
List<User> resultUserList = users.stream()
.filter(user -> user.getId() == 1)
.collect(Collectors.toList());
if (resultUserList.size() != 1) {
throw new IllegalStateException();
}
User resultUser = resultUserList.get(0);
Streams are created with an initial choice of sequential or parallel execution. (For example, Collection.stream() creates a sequential stream, and Collection.
Stream API可以极大提高Java程序员的生产力,让程序员写出高效率、干净、简洁 的代码。 这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以 在 ...
No storage. A stream is not a data structure that stores elements; instead, it conveys elements from a source such as a data structure, an array, a generator ...
May 14, 2021 ... In this comprehensive tutorial, we'll go through the practical uses of Java 8 Streams from creation to parallel execution. To understand this ...
Oct 9, 2019 ... Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods ...
Mar 18, 2020 ... Java Stream Specializations. From what we discussed so far, Stream is a stream of object references. However, there are also the IntStream, ...
Jul 31, 2014 ... Learn Java 8 streams by example: functional programming with filter, map, flatMap, reduce, collect, lambdas, sequential and parallel streams ...
Apr 28, 2019 ... The Java Stream API refers to the functional stream processing API added to Java in Java 8. The Java Stream API provides a functional ...
Create a custom Collector. public static <T> Collector<T, ?, T> toSingleton() { return Collectors.collectingAndThen( Collectors.toList(), list -> { if ...