使用 Java 8 中的特性,转换列表所有值的最简洁方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19676750/
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-12 19:19:26  来源:igfitidea点击:

Using the features in Java 8, what is the most concise way of transforming all the values of a list?

javalistcollectionslambdajava-8

提问by The Coordinator

Using the new features of Java 8, what is the most concise way of transforming all the values of a List<String>?

使用 Java 8 的新特性,转换 a 的所有值的最简洁方法是List<String>什么?

Given this:

鉴于这种:

List<String> words = Arrays.asList("Apple", "Ananas", "Mango", "Banana", "Beer");

I am currently doing this:

我目前正在这样做:

for (int n = 0; n < words.size(); n++) {
    words.set(n, words.get(n).toUpperCase());
}

How can the new Lambdas, Collections and Streams API in Java 8 help:

Java 8 中新的 Lambdas、Collections 和 Streams API 如何提供帮助:

  1. transform the values in-place (without creating a new list)

  2. transform the values into a new result list.

  1. 就地转换值(无需创建新列表)

  2. 将值转换为新的结果列表。

采纳答案by The Coordinator

This is what I came up with:

这就是我想出的:

Given the list:

鉴于名单:

List<String> keywords = Arrays.asList("Apple", "Ananas", "Mango", "Banana", "Beer");

(1) Transforming them in place

(1) 就地改造

Maybe I am missing it, there does not seem to be a 'apply' or 'compute' method that takes a lambda for List. So, this is the same as with old Java. I can not think of a more concise or efficient way with Java 8.

也许我错过了它,似乎没有一个“应用”或“计算”方法可以为 List 使用 lambda。因此,这与旧 Java 相同。我想不出更简洁或有效的 Java 8 方法。

for (int n = 0; n < keywords.size(); n++) {
    keywords.set(n, keywords.get(n).toUpperCase());
}

Although there is this way which is no better than the for(..) loop:

虽然有这种方式并不比 for(..) 循环好:

IntStream.range(0,keywords.size())
    .forEach( i -> keywords.set(i, keywords.get(i).toUpperCase()));

(2) Transform and create new list

(2) 转换并创建新列表

List<String> changed = keywords.stream()
    .map( it -> it.toUpperCase() ).collect(Collectors.toList());

回答by jsrmalvarez

Maybe using the new stream concept in collections:

也许在集合中使用新的流概念:

List<String> keywords = Arrays.asList("Apple", "Ananas", "Mango", "Banana", "Beer");
//(1)
keywords = keywords.stream().map(s -> s.toUpperCase()).collect(Collectors.toList());
//(2)
List<String> uppercaseKeywords = keywords.stream().map(s -> s.toUpperCase()).collect(Collectors.toList());