'Java 8 stream add 1 to each element and remove if element is 5 in the list

List<Integer> list = new ArrayList<>();
for(int i=0;i<20;i++) {
   list.add(i)
}

Here I would like to add +1 to each element and remove element from the list if the element is 5.



Solution 1:[1]

list.stream()
    .filter(x -> x != 5)           // filter out the number 5 before incrementing the numbers. Put this statement 2 lines below if you want to remove 5 after incrementing
    .map(x -> x + 1)               // add 1 to each number
    .collect(Collectors.toList()); // create list from stream

Solution 2:[2]

You can use the removeIf method, is a simple method of the ArrayList Class. You can follow this link for a clear explanation. https://www.geeksforgeeks.org/arraylist-removeif-method-in-java/

You can use this method sooner or later according to your needs.

List<Integer> list = new ArrayList<>();

for(int i = 0; i < list.size(); i++) {
   list.set(i, list.get(i) + 1);
}

list.removeIf(n -> (n == 5)); //removeIf method

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel
Solution 2 Dorian Gray