Stream 编程

Stream 编程

String[] Stream

Arrays.stream(lines.split("\\s+"))
	.map(String::toUpperCase)
	.toArray(String[]::new)

Integer[] 或 int[] stream

int[] num = {1, 2, 3, 4, 5};

Integer[] result = Arrays.stream(num)
	.map(x -> x * 2)
	.boxed()
	.toArray(Integer[]::new);

int[]

Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
int[] result = stream.map2Int(x -> x).toArray();

lambda 引用外部变量

lambda 引用外部变量为什么必须声明为 final ?

Local variables in Java have until now been immune to race conditions and visibility problems because they are accessible only to the thread executing the method in which they are declared. But a lambda can be passed from the thread that created it to a different thread, and that immunity would therefore be lost if the lambda, evaluated by the second thread, were given the ability to mutate local variables.

Lambdas: local variables need final, instance variables don’t

字段和本地变量的本质区别在于:当 JVM 创建 lambda 实例的时候,本地变量会被拷贝一份

You may be asking yourself why local variables have these restrictions. First, there’s a key difference in how instance and local variables are implemented behind the scenes. Instance variables are stored on the heap, whereas local variables live on the stack. If a lambda could access the local variable directly and the lambda were used in a thread, then the thread using the lambda could try to access the variable after the thread that allocated the variable had deallocated it. Hence, Java implements access to a free local variable as access to a copy of it rather than access to the original variable. This makes no difference if the local variable is assigned to only once—hence the restriction. Second, this restriction also discourages typical imperative programming patterns (which, as we explain in later chapters, prevent easy parallelization) that mutate an outer variable.