Using functions in Java 8, what is the most concise way to convert all list values?

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

Considering 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 the new Lambdas, Collections, and Streams APIs can help in Java 8:

  • convert values ​​in place (without creating a new list)

  • converts values ​​to a new list of results.

+7
java collections list lambda java-8
source share
2 answers

Here is what I came up with:

Given the list:

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

(1) Converting them into place

Maybe I miss him, there seems to be no "apply" or "compute" method that accepts a lambda for List. Thus, it is the same as with old Java. I cannot come up with 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 a way that is no better than a for (..) loop:

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

(2) Converting and creating a new list

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

It is possible to use the concept of a new stream 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()); 
0
source share

All Articles