如何在 Java 8 Streaming API 的集合中保留未过滤的数据?数据、如何在、Streaming、Java

2023-09-07 01:24:33 作者:未来很迷茫

我的输入序列是:[1,2,3,4,5]

结果应该是:[1,12,3,14,5]

即偶数加 10,但奇数保持不变.

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

这是我尝试过的:

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;
    }

当我调用这个方法时,

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

我得到 [12, 14].我想知道如何包含未 filtered 渗入但不应应用 map 的值.

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.

推荐答案

你可以在 map 中使用三元运算符,这样你应用的函数要么是奇数值的恒等式,要么对于偶数值,将值增加 10:

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.

请注意,如果您不关心就地修改列表,则可以直接使用 replaceAll,因为您正在执行从类型 T 到 T 的映射.

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]