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!