2

In the code, I want to modify variable i by map() method:

Integer[] seq = {1, 3, 4, 1, 8, 11};

List<Integer> seqInt = Arrays.asList(seq);
List<Integer> seqFiltered = seqInt.stream().filter(i -> i%2!=0)
                                      .map(i -> i++)
                                      .collect(Collectors.toList());
System.out.println(seqFiltered);

However, it outputs [1, 3, 1, 11] instead of [2, 4, 2, 12] which could be obtained from map(i -> i+1)

  • 1
    In addition to nullpointer's answer for more details: [Is there a difference between x++ and ++x in java?](https://stackoverflow.com/questions/1094872/is-there-a-difference-between-x-and-x-in-java) – Malte Hartwig Sep 10 '18 at 12:21

1 Answers1

4

Just make use of the pre-increment instead of post-increment operator.

List<Integer> seqFiltered = seqInt.stream()
                                  .filter(i -> i%2!=0)
                                  .map(i -> ++i)
                                  .collect(Collectors.toList());

also, you can make use of the Arrays.stream to use the Integer array as a stream

List<Integer> seqFiltered = Arrays.stream(seq)
                                  .filter(i -> i % 2 != 0)
                                  .map(i -> ++i)
                                  .collect(Collectors.toList());
Naman
  • 27,789
  • 26
  • 218
  • 353
  • 3
    It would be more intuitive (in my opinion) to use `map(i -> i + 1)` instead, especially as `i` is discarded, so the side-effect of the pre-increment operator (increasing `i` as well) is not used at all – Mark Rotteveel Sep 10 '18 at 14:23