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!


Web Apps, SPA, PWA with vanilla Java Script (ES 6+), CSS 3 and WebStandards only. As simple as possible, but not simpler. See you at: (Progressive) Web apps, Single Page Apps and WebStandards airhacks workshops at MUC airport, Winter Edition

airhacks.fm the podcast:

Stay in touch: airhacks.news.

Comments:

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