使用 java 8 api 打印列表项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31432948/
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
Print list items with java 8 api
提问by vicolored
I can use something like :
我可以使用类似的东西:
.forEach(System.out::print)
to print my list items but if I have another operation to do before printing I can't use it like :
打印我的列表项,但如果我在打印前还有其他操作要做,我不能像这样使用它:
mylist.replaceAll(s -> s.toUpperCase()).forEach(System.out::print)
I'm getting an error : void cannot be dereferenced
我收到一个错误:void 不能取消引用
采纳答案by Holger
You have to decide. When you want to modify the list, you can't combine the operations. You need two statements then.
你必须决定。当你想修改列表时,你不能组合操作。那么你需要两个语句。
myList.replaceAll(String::toUpperCase);// modifies the list
myList.forEach(System.out::println);
If you just want to map
values before printing without modifying the list, you'll have to use a Stream
:
如果您只想map
在打印之前不修改列表的值,则必须使用Stream
:
myList.stream().map(String::toUpperCase).forEachOrdered(System.out::println);
回答by Aniket Thakur
If you want to print and save modified values simultaneously you can do
如果你想同时打印和保存修改后的值,你可以这样做
List<String> newValues = myList.stream().map(String::toUpperCase)
.peek(System.out::println).collect(Collectors.toList());
回答by Summved Jain
The best way to print all of them in one go is
一次性打印所有这些的最佳方法是
Arrays.toString(list.toArray())
Arrays.toString(list.toArray())
回答by Q10Viking
You can look at the following example that can be executed in java8 environment.
可以看下面的例子,可以在java8环境下执行。
import java.util.Arrays;
import java.util.List;
public class Main{
public static void main(String[] args){
// create a list
List<String> mylist = Arrays.asList("Hello","World");
mylist.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
}
}
/*output
HELLO
WORLD
*/