gpt4 book ai didi

java - 使用流转换和过滤 Java Map

转载 作者:IT老高 更新时间:2023-10-28 20:53:18 26 4
gpt4 key购买 nike

我有一个想要转换和过滤的 Java map 。作为一个简单的例子,假设我想将所有值转换为整数,然后删除奇数项。

Map<String, String> input = new HashMap<>();
input.put("a", "1234");
input.put("b", "2345");
input.put("c", "3456");
input.put("d", "4567");

Map<String, Integer> output = input.entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> Integer.parseInt(e.getValue())
))
.entrySet().stream()
.filter(e -> e.getValue() % 2 == 0)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));


System.out.println(output.toString());

这是正确的并产生:{a=1234, c=3456}

但是,我不禁想知道是否有办法避免两次调用 .entrySet().stream()

有没有一种方法可以同时执行转换和过滤操作,并且在最后只调用一次 .collect()

最佳答案

是的,您可以将每个条目映射到另一个临时条目,该条目将保存键和解析的整数值。然后您可以根据每个条目的值过滤它们。

Map<String, Integer> output =
input.entrySet()
.stream()
.map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), Integer.valueOf(e.getValue())))
.filter(e -> e.getValue() % 2 == 0)
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue
));

请注意,我使用 Integer.valueOf 而不是 parseInt 因为我们实际上想要一个装箱的 int


如果您有幸使用 StreamEx图书馆,你可以很简单地做到这一点:

Map<String, Integer> output =
EntryStream.of(input).mapValues(Integer::valueOf).filterValues(v -> v % 2 == 0).toMap();

关于java - 使用流转换和过滤 Java Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35486826/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com