Java 8 中“System.out::println”有什么用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31020269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:32:07  来源:igfitidea点击:

What is the use of "System.out::println" in Java 8

javajava-8

提问by prime

I saw a code in java 8 to iterate a collection.

我在java 8中看到了一个代码来迭代一个集合。

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
numbers.forEach(System.out::println);

What is the functionality of System.out::println? And how the above code can iterate through the List.

的功能是System.out::println什么?以及上面的代码如何遍历 List。

And what is the use of the operator ::, Where else we can use this operator ?

运算符的用途是::什么,我们还能在哪里使用这个运算符?

采纳答案by Konstantin Yovkov

It's called a "method reference"and it's a syntactic sugar for expressions like this:

它被称为“方法引用”,它是如下表达式的语法糖:

numbers.forEach(x -> System.out.println(x));

Here, you don't actually needthe name xin order to invoke printlnfor each of the elements. That's where the method reference is helpful - the ::operator denotes you will be invoking the printlnmethod with a parameter, which name you don't specify explicitly:

在这里,您实际上不需要名称x来调用println每个元素。这就是方法引用有用的地方 -::运算符表示您将println使用参数调用方法,您没有明确指定该名称:

numbers.forEach(System.out::println);