I am reading the newly released Java 8 in Action and found there is a piece of code pasted from Chapter 5 not compiling:
List<Integer> numbers1 = Arrays.asList(1, 2, 3);
List<Integer> numbers2 = Arrays.asList(3, 4);
List<int[]> pairs =
numbers1.stream()
.flatMap((Integer i) -> numbers2.stream()
.map(j -> new int[]{i, j})
)
.collect(toList());
Eclipse says: "Type mismatch: cannot convert from List<Object>
to List<int[]>
"
And after comparing with what the author gave on Github, the following compiled:
List<Integer> numbers1 = Arrays.asList(1, 2, 3);
List<Integer> numbers2 = Arrays.asList(3, 4);
List<int[]> pairs =
numbers1.stream()
.flatMap((Integer i) -> numbers2.stream()
.map((Integer j) -> new int[]{i, j})
)
.collect(toList());
The only change is from "j" to "(Integer j)".
But isn't the first version completely equivalent to the second with the syntax sugar provided by Java 8? Why does Java refuse to compile it?
Thanks
BTW:
java -version
java version "1.8.0_20"
Java(TM) SE Runtime Environment (build 1.8.0_20-b26)
Java HotSpot(TM) Client VM (build 25.20-b23, mixed mode)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…