I can not add the number 1 to each list item. What is the problem? How to do the same with Stream.api?

List<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); numbers.add(5); for (Integer integer: numbers){ integer=integer+1; } } 

    1 answer 1

    The type Integer is immutable ; you cannot change the value of the fields of this object. Every time you change an object of this type in any way, you actually just get a new object.

     a = a + 1; // что вы пишите a = Integer.valueOf(a + 1); // что происходит на самом деле 

    In the for (Integer integer: numbers) loop, you assign the integer variable a reference to the object stored in the list, then assign this variable a reference to another object (conventionally integer+1 ). The variable integer link has changed. Naturally, this does not affect the list.

    To make your cycle work, put new objects in the cells of the list explicitly:

      for (int i = 0; i < numbers.size(); i++){ numbers.set(i, numbers.get(i) + 1); // new Integer (numbers.get(i) + 1) } 

    or, if you are so sweet to the Stream API, make a whole new list

      numbers = numbers.stream() .map(x -> x +1) .collect(Collectors.toList());