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

前端 未结 1 1271
梦毁少年i
梦毁少年i 2020-12-11 10:08

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

相关标签:
1条回答
  • 2020-12-11 10:56

    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]
    
    0 讨论(0)
提交回复
热议问题