Using the features in Java 8, what is the most concise way of transforming all the values of a list?

47,414

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());
Share:
47,414
The Coordinator
Author by

The Coordinator

I am the protagonist in many popular Java-based business and hobby codebase box office hits. As an ambidextrous hard-partying and swinging hippie programmer, I save the world from code bugs and thaw cryogenically frozen greatness from my colleagues tortured and uncompiled source - while writing great code! Not only have I actually met Borat, I also have experience with Java, Groovy, Python, Fortran, QBasic, Bash, DOS and just about anything else required to get the job done in a multidisciplinary, undisciplined and uncouth-although-amazing software environment. My big project will be the Oz programming language. When it materializes, all other programming domains will crumble before the all-powerful, syntactically beautiful and functionally implicit Oz! I suppose I would then be the Wizard of Oz ;-)

Updated on November 08, 2020

Comments

  • The Coordinator
    The Coordinator over 3 years

    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.