'Find' method for Iterable
Nir Lisker
nlisker at gmail.com
Mon Sep 14 18:56:27 UTC 2020
Hi,
This has probably been brought up at some point. When we need to find an
item in a collection based on its properties, we can either do it in a
loop, testing each item, or in a stream with filter and findFirst/Any.
I would think that a method in Iterable<T> be useful, along the lines of:
public <T> Optional<T> find(Predicate<T> condition) {
Objects.requireNonNull(condition);
for (T t : this) {
if (condition.test(t)) {
return Optional.of(t);
}
}
return Optional.empty();
}
With usage:
list.find(person -> person.id == 123456);
There are a few issues with the method here such as t being null in
null-friendly collections and the lack of bound generic types, but this
example is just used to explain the intention.
It will be an alternative to
list.stream().filter(person -> person.id == 123456).findAny/First()
(depending on if the collection is ordered or not)
which doesn't create a stream, similar to Iterable#forEach vs
Stream#forEach.
Maybe with pattern matching this would become more appetizing.
- Nir
More information about the core-libs-dev
mailing list