I'm trying to migrate from Guava to Java 8 Streams, but can't figure out how to deal with iterables. Here is my code, to remove empty strings from the iterable:
Iterable<String> list = Iterables.filter(
raw, // it's Iterable<String>
new Predicate<String>() {
@Override
public boolean apply(String text) {
return !text.isEmpty();
}
}
);
Pay attention, it's an Iterable
, not a Collection
. It may potentially contain an unlimited amount of items, I can't load it all into memory. What's my Java 8 alternative?
BTW, with Lamba this code will look even shorter:
Iterable<String> list = Iterables.filter(
raw, item -> !item.isEmpty()
);
Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.
The filter() operation does not modify the original array. Because the filter() method returns a new array, we can chain the filter result with other iterative methods such as sort() and map() .
A stream interface's filter() method identifies elements in a stream that satisfy a criterion. It is a stream interface intermediate operation. Notice how it accepts a predicate object as a parameter. A predicate is a logical interface to a functional interface.
You can implement Iterable
as a functional interface using Stream.iterator()
:
Iterable<String> list = () -> StreamSupport.stream(raw.spliterator(), false)
.filter(text -> !text.isEmpty())
.iterator();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With