Converting an Iterator or Spliterator into a Stream

The useful utility class: StreamSupport converts Spliterator into a Stream.

Also an java.util.Iterator could be easily converted into a Spliterator using the Spliterators utility.

Particularly interesting is the combination with Java EE. An interface Greeter:


public interface Greeter {
    String getMessage();
}

Can be injected as an Instance, which implements the Iterable interface. This allows the conversion into a stream:

public class GreeterExposer {

    @Inject
    Instance<Greeter> greeter;

    @Produces
    public Stream<Greeter> expose() {
        return StreamSupport.stream(greeter.spliterator(), false);
    }

}

A Stream greatly simplifies the direct access and transformation to the contents. The output of all realizations of this interface could be easily joined into a single String:

@Stateless
public class GreetingsService {

    @Inject
    Stream<Greeter> greaters;

    public String allGreetings() {
        return greaters.
        map(g -> g.getMessage()).
        collect(Collectors.joining(","));
    }

}

Three concrete Greeting classes would output something like: "a bad day,leave me alone...,Have a nice day!"

See you at Java 8 with Java EE 7 or Virtual Dedicated Workshops / consulting!


NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 8, Java 9: Bootstrap, Effective, Architectures, Single Page Apps, Progressive Web Apps, HTML 5, ES 6, CSS 3 and Microservices

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License