使用流转换和过滤Java Map [英] Transform and filter a Java Map with streams
问题描述
我有一个Java Map,我想对其进行转换和过滤.作为一个简单的示例,假设我想将所有值都转换为Integers,然后删除奇数项.
I have a Java Map that I'd like to transform and filter. As a trivial example, suppose I want to convert all values to Integers then remove the odd entries.
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}
This is correct and yields: {a=1234, c=3456}
但是,我不禁想知道是否存在避免两次调用.entrySet().stream()
的方法.
However, I can't help but wonder if there's a way to avoid calling .entrySet().stream()
twice.
有没有办法执行转换和过滤操作,并且最后只调用一次.collect()
?
Is there a way I can perform both transform and filter operations and call .collect()
only once at the end?
推荐答案
是的,您可以将每个条目映射到另一个包含键和已解析的整数值的临时条目.然后,您可以根据每个条目的值对其进行过滤.
Yes, you can map each entry to another temporary entry that will hold the key and the parsed integer value. Then you can filter each entry based on their value.
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
));
请注意,由于我们实际上想要装箱的int
,所以我使用Integer.valueOf
而不是parseInt
.
Note that I used Integer.valueOf
instead of parseInt
since we actually want a boxed int
.
如果您愿意使用 StreamEx 库,则可以非常简单地做到这一点:
If you have the luxury to use the StreamEx library, you can do it quite simply:
Map<String, Integer> output =
EntryStream.of(input).mapValues(Integer::valueOf).filterValues(v -> v % 2 == 0).toMap();
这篇关于使用流转换和过滤Java Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!