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

Posted by Saint Hill on Stack Overflow See other posts from Stack Overflow or by Saint Hill
Published on 2013-10-31T03:25:02Z Indexed on 2013/10/31 3:53 UTC
Read the original article Hit count: 193

Filed under:
|
|
|

I am trying to determine the correct way of transforming 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:

String function(String s){ 
    return [some change made to value of s];
}

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about collections