Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to keep the unfiltered data in the collection in Java 8 Streaming API?

My Input Sequence is : [1,2,3,4,5]

Result should be : [1,12,3,14,5]

That is even numbers are incremented by 10, but odd values are left intact.

Here is what I tried:

public static List<Integer> incrementEvenNumbers(List<Integer> arrays){
        List<Integer> temp = 
          arrays.stream()
                .filter(x->x%2==0)
                .map(i -> i+10)
                .collect(Collectors.toList());
        return temp;
    }

when I call this method,

System.out.println(incrementEvenNumbers(Arrays.asList(1,2,3,4,5)));

I get [12, 14]. I am wondering how to include the values not filtered to seep in but the map should not be applied for it.

like image 664
brain storm Avatar asked Mar 16 '23 13:03

brain storm


1 Answers

You can use a ternary operator with map, so that the function you apply is either the identity for odd values, or the one that increments the value by 10 for even values:

 List<Integer> temp = arrays.stream()
                            .map(i -> i % 2 == 0 ? i+10 : i)
                            .collect(Collectors.toList());

The problem, as you saw, is that filter will remove the elements so when a terminal operation will be called, they will be filtered by the predicate.

Note that if you don't care modifying the list in place, you can use replaceAll directly, as you are doing a mapping from a type T to T.

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
list.replaceAll(i -> i % 2 == 0 ? i+10 : i); //[1, 12, 3, 14, 5]
like image 140
Alexis C. Avatar answered Apr 08 '23 07:04

Alexis C.