Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a lambda be used to change a List's values in-place ( without creating a new list)?

I am trying to determine the correct way of changing all the values in a List using the new lambdas feature in the upcoming release of Java 8 without creating a **new** List.

This pertains to times when a List is passed in by a caller and needs to have a function applied to change all the contents to a new value. For example, the way Collections.sort(list) changes a list in-place.

What is the easiest way given this transforming function, and this starting list, to apply the function to all the values in the original list without making a new list?

String function(String s){ 
    return s.toUppercase(); // or something else more complex
}

List<String> list = Arrays.asList("Bob", "Steve", "Jim", "Arbby");

The usual way of applying a change to all the values in-place was this:

for (int i = 0; i < list.size(); i++) {
    list.set(i, function( list.get(i) );
}

Does lambdas and Java 8 offer:

  • an easier and more expressive way?
  • a way to do this without setting up all the scaffolding of the for(..) loop?
like image 441
The Coordinator Avatar asked Oct 31 '13 03:10

The Coordinator


2 Answers

    List<String> list = Arrays.asList("Bob", "Steve", "Jim", "Arbby");
    list.replaceAll(String::toUpperCase);
like image 151
Stuart Marks Avatar answered Oct 21 '22 22:10

Stuart Marks


With a popular library Guava you can create a computing view on the list which doesn't allocate memory for a new array, i.e.:

upperCaseStrings = Lists.transform(strings, String::toUpperCase)

A better solution is proposed by @StuartMarks, however, I am leaving this answer as it allows to also change a generic type of the collection.


Another option is to declare a static method like mutate which takes list and lambda as a parameter, and import it as a static method i.e.:


mutate(strings, String::toUpperCase);

A possible implementation for mutate:

@SuppressWarnings({"unchecked"})
public static  List mutate(List list, Function function) {
    List objList = list;

    for (int i = 0; i 

like image 20
Andrey Chaschev Avatar answered Oct 21 '22 21:10

Andrey Chaschev