McAnder McAnder - 18 days ago 7
Java Question

Java 8 Lambda stack bleed

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;


public class StackBleed {
public static int check(String s) {
if (s.equals("lambda")) {
throw new IllegalArgumentException();
}
return s.length();
}

@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
// List lengths = new ArrayList();
List<String> argList = Arrays.asList(args);


Stream lengths2 = argList.stream().map((String name) -> check(name));
}
}


So I was checking out this article http://www.takipiblog.com/2014/03/25/the-dark-side-of-lambda-expressions-in-java-8/ and wrote similar class, but JDK 8 approach didn't yield expected exception. I was wondering if they have changed something in JDK 8u5?

Answer

You're only calling a non-terminal operation on the stream. So your code doesn't consume the data from the stream. All it does is saying: "when a terminal operation will be called, you'll have to map the strings using the check() method".

Use

List<Integer> transformed = 
    argList.stream().map((String name) -> check(name)).collect(Collectors.toList());

for example, and then the call to collect(), which is a terminal operation, will trigger the iteration on the stream elements and the transformation of its elements.

Comments