Why are Java Streams once-off?

I have some recollections from the early design of the Streams API that might shed some light on the design rationale. Back in 2012, we were adding lambdas to the language, and we wanted a collections-oriented or “bulk data” set of operations, programmed using lambdas, that would facilitate parallelism. The idea of lazily chaining operations … Read more

Using streams to convert a list of objects into a string obtained from the toString method

One simple way is to append your list items in a StringBuilder List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); StringBuilder b = new StringBuilder(); list.forEach(b::append); System.out.println(b); you can also try: String s = list.stream().map(e -> e.toString()).reduce(“”, String::concat); Explanation: map converts Integer stream to String stream, then its reduced as concatenation of all the elements. … Read more

Why does Iterable not provide stream() and parallelStream() methods?

This was not an omission; there was detailed discussion on the EG list in June of 2013. The definitive discussion of the Expert Group is rooted at this thread. While it seemed “obvious” (even to the Expert Group, initially) that stream() seemed to make sense on Iterable, the fact that Iterable was so general became … Read more

Using Java 8’s Optional with Stream::flatMap

Java 9 Optional.stream has been added to JDK 9. This enables you to do the following, without the need of any helper method: Optional<Other> result = things.stream() .map(this::resolve) .flatMap(Optional::stream) .findFirst(); Java 8 Yes, this was a small hole in the API, in that it’s somewhat inconvenient to turn an Optional<T> into a zero-or-one length Stream<T>. … Read more

Filter Java Stream to 1 and only 1 element

Create a custom Collector public static <T> Collector<T, ?, T> toSingleton() { return Collectors.collectingAndThen( Collectors.toList(), list -> { if (list.size() != 1) { throw new IllegalStateException(); } return list.get(0); } ); } We use Collectors.collectingAndThen to construct our desired Collector by Collecting our objects in a List with the Collectors.toList() collector. Applying an extra finisher … Read more

Java 8 Streams: multiple filters vs. complex condition

The code that has to be executed for both alternatives is so similar that you can’t predict a result reliably. The underlying object structure might differ but that’s no challenge to the hotspot optimizer. So it depends on other surrounding conditions which will yield to a faster execution, if there is any difference. Combining two … Read more

tech