Using the new features of Java 8, what is the most concise way of transforming all the values of 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:
transform the values in-place (without creating a new list)
transform the values into a new result list.
This is what I came up with:
Given the list:
List<String> keywords = Arrays.asList("Apple", "Ananas", "Mango", "Banana", "Beer");
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());
}
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()));
List<String> changed = keywords.stream()
.map( it -> it.toUpperCase() ).collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With