yegor256
yegor256

Reputation: 105043

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

Upvotes: 14

Views: 8015

Answers (1)

shmosel
shmosel

Reputation: 50716

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

Iterable<String> list = () -> StreamSupport.stream(raw.spliterator(), false)
        .filter(text -> !text.isEmpty())
        .iterator();

Upvotes: 13

Related Questions