Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace Iterables.filter() with Streams?

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()
);
like image 392
yegor256 Avatar asked Jan 30 '17 07:01

yegor256


People also ask

How do you filter objects with a stream?

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.

Does stream filter modify the original array?

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() .

What kind of interface does the filter method in a stream accept?

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.


Video Answer


1 Answers

You can implement Iterable as a functional interface using Stream.iterator():

Iterable<String> list = () -> StreamSupport.stream(raw.spliterator(), false)
        .filter(text -> !text.isEmpty())
        .iterator();
like image 200
shmosel Avatar answered Sep 18 '22 07:09

shmosel