Adam Bien's Weblog

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 workshop: HTML 5 and JavaScript Essentials, Three days in April 2017: from Java EE 7 Architectures over Microservices to Performance, Troubleshooting and Monitoring
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

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