JDK-8277306 : stream with sorted() and concat() causes some ops not to be lazy
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util.stream
  • Affected Version: 11,17,18
  • Priority: P4
  • Status: New
  • Resolution: Unresolved
  • OS: generic
  • CPU: generic
  • Submitted: 2021-11-15
  • Updated: 2021-11-17
Related Reports
Relates :  
Description
A DESCRIPTION OF THE PROBLEM :
Related issue : https://bugs.openjdk.java.net/browse/JDK-8042355 

A similar report was raised in the issue linked above but it still seems to be happening when a call to concat() is introduced in the pipeline. 


EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
'peek' is called only once, i.e, output should be,

PEEK: a
result a

ACTUAL -
'peek' is called for all elements. i'e, output is,

PEEK: a
PEEK: ab
PEEK: abc
PEEK: abcd
result a


---------- BEGIN SOURCE ----------
public class Blah
{
	public static void main(String[] args)
	{
		Stream<String> stream = Stream.of("a", "ab", "abc", "abcd")
//                .sorted() // uncommenting this cause 'peek' to be called on all elements 
				.peek(s -> System.out.println("PEEK: " + s));

//        Stream<String> finalStream = stream;
		Stream<String> finalStream = Stream.concat(stream, Stream.of());

		String result = finalStream.findFirst().orElseThrow();

		System.out.println("result " + result);
	}
}

---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
collect the sorted result into a list and start a new pipeline


Comments
The observations on Windows 10: JDK 11: Failed, 'peek' is called for all elements. JDK 17: Failed. JDK 18ea+1: Failed.
17-11-2021