31

I want to transform a list of strings to upper case.

Here's my code to do this:

List<String> list = Arrays.asList("abc", "def", "ghi");
List<String> upped = list.stream().map(String::toUpperCase).collect(Collectors.toList());

Is there a simpler/better way to do this?

Roman C
  • 49,761
  • 33
  • 66
  • 176
lapots
  • 12,553
  • 32
  • 121
  • 242

1 Answers1

67

You have not actually transformed the list; you have created a new list.

To transform the list in one small method call, use List#replaceAll():

list.replaceAll(String::toUpperCase);
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Does this actually assign the transformed Strings to their respectful positions in the list? I only ask because I'm used to the string format `s=s.replaceAll()` but I'm not familiar with this implementation for List. Sounds like good info :) – Calvin P. Feb 14 '16 at 18:24
  • 2
    @CalvinP.yes - it performs an in-place conversion on each element using the provided lambda, so element order is preserved. – Bohemian Feb 14 '16 at 18:26