16

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:

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

  2. transform the values into a new result list.

The Coordinator
  • 13,007
  • 11
  • 44
  • 73

2 Answers2

52

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

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()));

(2) Transform and create new list

List<String> changed = keywords.stream()
    .map( it -> it.toUpperCase() ).collect(Collectors.toList());
The Coordinator
  • 13,007
  • 11
  • 44
  • 73
0

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());
  • (1) does not work since stream().map( ...) only returns another stream ... but (2) does work. Not sure I like the Arrays.asList(...) part though. – The Coordinator Oct 30 '13 at 08:33
  • Less cumbersome. I corrected (1). Is similar to (2) but I think all the ways go through collect method or array conversion. – jsrmalvarez Oct 30 '13 at 08:38
  • (1) now produces a new list ... I was hoping I am missing something or maybe there is some other API that takes a list and a function to apply :( (just shed a tear for Java 8) – The Coordinator Oct 30 '13 at 08:40
  • 2
    Well, so does toUppercase(), which doesn't mutate the String but returns a new one. Maybe it's the Java way, you know, don't worry about low level details, there's a garbage collector for cleaning your useless objects and magic optimizations somewhere :D – jsrmalvarez Oct 30 '13 at 08:52
  • I am only thinking of the case where a List is passed in and the modifications need to be done to the same List to be captured by the caller, as in cases such as Collections.sort(...) or some other list transforming function. Otherwise, yes, the Java magic should take care of everything :) – The Coordinator Oct 30 '13 at 09:44