How to update each item in a list in Java 8 using Stream API

I have a list defined as follows:

List<Integer> list1 = new ArrayList<>();
list1.add(1); 
list1.add(2);

How can I increase each list item by one (i.e. end the List [2,3]) using the Java 8 Stream API without creating a new list?

+4
source share
4 answers

When you create Streamfrom List, you are not allowed to change the source Listfrom Stream, as indicated in the “Non-Intervention” in the package documentation . Failure to comply with this restriction may result in damage to the structure ConcurrentModificationExceptionor, even worse, damaged structure without exception.

Java - , , .. ,

IntStream.range(0, list1.size()).forEach(ix -> list1.set(ix, list1.get(ix)+1));

Stream. ,

list1.replaceAll(i -> i + 1);

List , Java 8, -. , , , Iterable.forEach, Collection.removeIf List.sort, , Stream API. , Map , .

. " API, - Java SE 8 " .

+16

. , , , Java 8: Math#incrementExact. ArithmeticException, int. , :

list1.replaceAll(Math::incrementExact);
+3

You can iterate over indices using IntStreamin combination with forEach:

IntStream.range(0,list1.size()).forEach(i->list1.set(i,list1.get(i)+1));

However, this is not very different from the normal cycle and is probably less readable.

+1
source

reassign the result to list1:

list1 = list1.stream().map(i -> i+1).collect(Collectors.toList());
0
source

Source: https://habr.com/ru/post/1691780/


All Articles