3

Well I'm digging through Java8 lambda and I'm facing following problem - lambda doesn't change data:

DamnLambda.class:

public static void inc ( List<Integer> list, Funtion<Integer,Integer> func) {

    for(Integer intr : list) {
        intr = func.apply(intr);
    }

Let's try to invoke:

List<Integer> l = Arrays.asList(1,2,3);

DamnLambda.inc(l, x -> x+=1);
System.out.println(l); //[1,2,3] ? Why not [2,3,4] ?

I can't understad why it doesn't change any data. I tried also different version of same functionality:

l.forEach(x -> x+1); //same thing, doesn't change the data.

What am I missing here?

3
  • 3
    Assigning a value to the loop iteration variable will have no effect and, in fact, should not be done. Commented Jul 6, 2014 at 23:55
  • 3
    You're missing the point of functional programming. You're not supposed to change the input. You're supposed to generate output that is a transformation of the input. Commented Jul 6, 2014 at 23:56
  • Well guys u got me, I was blindly trying to perform some lambda operations on the list and forgotten about one of the primal rules. Btw. code compiles. Commented Jul 6, 2014 at 23:57

3 Answers 3

8

How about:

list.replaceAll(x -> x+1);
Sign up to request clarification or add additional context in comments.

1 Comment

It's even better than previous one, but I marked previous as an answer because he reflected the situation I had in mind. I was trying to understand usage lambda in practice.
4

Brian Goetz' answer is clearly the one to use if you want to mutate a list in-place. An alternative, which alfasin's answer seems to be describing, is to create a new list containing the modified values. The way to do with using lambda and streams is:

List<Integer> result =
    list.stream()
        .map(i -> i + 1)
        .collect(Collectors.toList());

1 Comment

veru useful, I'm planning to go through streams today :)
3

Change inc() to:

public static List<Integer> inc ( List<Integer> list, Funtion<Integer,Integer> func) {

    List<Integer> result = new ArrayList<Integer>();
    for(Integer intr : list) {
        result.add(func.apply(intr));
    }
    return result;
}

and then call:

l = DamnLambda.inc(l, x -> x+=1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.