使用Java 8中的功能,转换列表的所有值的最简洁方法是什么? [英] Using the features in Java 8, what is the most concise way of transforming all the values of a list?
问题描述
使用Java 8的新功能,转换 List< String>
的所有值的最简洁方法是什么?
Using the new features of Java 8, what is the most concise way of transforming all the values of a List<String>
?
鉴于此:
List<String> words = Arrays.asList("Apple", "Ananas", "Mango", "Banana", "Beer");
我目前正在这样做:
for (int n = 0; n < words.size(); n++) {
words.set(n, words.get(n).toUpperCase());
}
Java 8中新的Lambdas,Collections和Streams API如何帮助:
How can the new Lambdas, Collections and Streams API in Java 8 help:
-
就地转换值(不创建新列表)
transform the values in-place (without creating a new list)
将值转换为新的结果列表。
transform the values into a new result list.
推荐答案
这就是我的想法:
鉴于清单:
List<String> keywords = Arrays.asList("Apple", "Ananas", "Mango", "Banana", "Beer");
(1)将它们转换为适当位置
也许我错过了它,似乎没有一个'apply'或'compute'方法,它将一个lambda用于List。所以,这与旧的Java相同。我无法想到使用Java 8更简洁或更有效的方法。
(1) Transforming them in place
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.
for (int n = 0; n < keywords.size(); n++) {
keywords.set(n, keywords.get(n).toUpperCase());
}
虽然这种方式并不比for(..)好循环:
Although there is this way which is no better than the for(..) loop:
IntStream.range(0,keywords.size())
.forEach( i -> keywords.set(i, keywords.get(i).toUpperCase()));
(2)转换并创建新列表
(2) Transform and create new list
List<String> changed = keywords.stream()
.map( it -> it.toUpperCase() ).collect(Collectors.toList());
这篇关于使用Java 8中的功能,转换列表的所有值的最简洁方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!