使用流转换和过滤 Java Map
我有一个想要转换和过滤的 Java 地图.作为一个简单的例子,假设我想将所有值转换为整数,然后删除奇数项.
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}
但是,我不禁想知道是否有办法避免两次调用 .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
));
请注意,我使用 Integer.valueOf
而不是 parseInt
因为我们实际上想要一个装箱的 int
.
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();
相关文章