【问题标题】:Transform and filter a Java Map with streams使用流转换和过滤 Java Map
【发布时间】:2016-05-30 22:27:00
【问题描述】:

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

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()?

【问题讨论】:

  • 我认为不可能。基于javadoc“一个流应该只被操作一次(调用中间或终端流操作)。这排除了例如“分叉”流,其中相同的源提供两个或多个管道,或者相同的多个遍历流。如果流实现检测到流正在被重用,它可能会抛出 IllegalStateException。"
  • @Namban 这不是问题所在。

标签: java java-8 java-stream collectors


【解决方案1】:

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

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();

【讨论】:

  • 虽然这是一种可能的hacky方式,但我觉得我们牺牲了几行代码的性能和可读性,不是吗?
  • @Nambari 我不明白为什么它是“hacky”。它只是一个地图过滤器。如果是显式使用AbstractMap.SimpleEntry,您可以创建另一个Pair,但我觉得这里合适,因为我们已经在处理地图了。
  • 我使用“hacky”只是因为我们正在跟踪“临时进入”,可能不是正确的术语。我喜欢 StreamEx 解决方案。
  • @Nambari,注意 StreamEx 在内部做同样的事情,它只是一个语法糖。
  • @TagirValeev:是的,我知道。当 API 不支持时,所有这些库都只是做语法糖。
【解决方案2】:

以更少的开销解决问题的一种方法是将映射和过滤下移到收集器。

Map<String, Integer> output = input.entrySet().stream().collect(
    HashMap::new,
    (map,e)->{ int i=Integer.parseInt(e.getValue()); if(i%2==0) map.put(e.getKey(), i); },
    Map::putAll);

这不需要创建中间Map.Entry 实例,甚至更好的是,将int 值的装箱推迟到值实际添加到Map 时,这意味着值被拒绝过滤器根本没有装箱。

与Collectors.toMap(…) 所做的相比,使用Map.put 而不是Map.merge 也简化了操作,因为我们事先知道我们不必在这里处理键冲突。

不过,只要你不想使用并行执行,你也可以考虑普通循环

HashMap<String,Integer> output=new HashMap<>();
for(Map.Entry<String, String> e: input.entrySet()) {
    int i = Integer.parseInt(e.getValue());
    if(i%2==0) output.put(e.getKey(), i);
}

或内部迭代变体:

HashMap<String,Integer> output=new HashMap<>();
input.forEach((k,v)->{ int i = Integer.parseInt(v); if(i%2==0) output.put(k, i); });

后者非常紧凑,至少在单线程性能方面与所有其他变体相当。

【讨论】:

  • 我赞成您对普通循环的推荐。仅仅因为你可以使用流并不意味着你应该。
  • @Jeffrey Bosboom:是的,旧的 for 循环仍然存在。虽然在映射的情况下,我喜欢使用 Map.forEach 方法来处理较小的循环,因为 (k,v)-&gt; 比声明一个 Map.Entry&lt;PossiblyLongKeyType,PossiblyLongValueType&gt; 变量以及可能另外两个变量来表示实际的键和值要好得多……
【解决方案3】:

Guava是你的朋友:

Map<String, Integer> output = Maps.filterValues(Maps.transformValues(input, Integer::valueOf), i -> i % 2 == 0);

请记住,output 是 input 的转换、过滤视图。如果您想独立操作它们,则需要制作副本。

【讨论】:

    【解决方案4】:

    您可以使用Stream.collect(supplier, accumulator, combiner) 方法来转换条目并有条件地累积它们:

    Map<String, Integer> even = input.entrySet().stream().collect(
        HashMap::new,
        (m, e) -> Optional.ofNullable(e)
                .map(Map.Entry::getValue)
                .map(Integer::valueOf)
                .filter(i -> i % 2 == 0)
                .ifPresent(i -> m.put(e.getKey(), i)),
        Map::putAll);
    
    System.out.println(even); // {a=1234, c=3456}
    

    在这里,在累加器中,我使用Optional 方法来应用转换和谓词,如果可选值仍然存在,我会将其添加到正在收集的地图中。

    【讨论】:

    • 非常接近my first variant,但我不认为使用Optional 是一个胜利......
    • @Holger 只是为了将所有内容放在一行中。无论如何,我没有看到你的答案。胜利(如果我们变得非常微妙)可能是 Optional.ofNullable() 允许空键。
    • 我们同时写作。 Optional 链实际上不是一行(或非常大的一行),而是一个表达式。但是从一定的表达式大小开始,语句 lambda 所需的两个花括号看起来不再那么昂贵了……
    【解决方案5】:

    另一种方法是从转换后的Map 中删除您不想要的值:

    Map<String, Integer> output = input.entrySet().stream()
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    e -> Integer.parseInt(e.getValue()),
                    (a, b) -> { throw new AssertionError(); },
                    HashMap::new
             ));
    output.values().removeIf(v -> v % 2 != 0);
    

    这假设您想要一个可变的Map 作为结果,如果不是,您可能可以从output 创建一个不可变的。


    如果您要将值转换为相同的类型,并且想要修改 Map 就地,使用 replaceAll 可能会更短:

    input.replaceAll((k, v) -> v + " example");
    input.values().removeIf(v -> v.length() > 10);
    

    这也假设input 是可变的。


    我不建议这样做,因为它不适用于所有有效的 Map 实现,并且将来可能会停止为 HashMap 工作,但您目前可以使用 replaceAll 并投射 HashMap 来更改值的类型:

    ((Map)input).replaceAll((k, v) -> Integer.parseInt((String)v));
    Map<String, Integer> output = (Map)input;
    output.values().removeIf(v -> v % 2 != 0);
    

    这也会给你类型安全警告,如果你尝试通过像这样的旧类型的引用从Map 中检索一个值:

    String ex = input.get("a");
    

    它会抛出一个ClassCastException。


    如果您希望大量使用它,您可以将第一个转换部分移动到一个方法中以避免样板:

    public static <K, VO, VN, M extends Map<K, VN>> M transformValues(
            Map<? extends K, ? extends VO> old, 
            Function<? super VO, ? extends VN> f, 
            Supplier<? extends M> mapFactory){
        return old.entrySet().stream().collect(Collectors.toMap(
                Entry::getKey, 
                e -> f.apply(e.getValue()), 
                (a, b) -> { throw new IllegalStateException("Duplicate keys for values " + a + " " + b); },
                mapFactory));
    }
    

    并像这样使用它:

        Map<String, Integer> output = transformValues(input, Integer::parseInt, HashMap::new);
        output.values().removeIf(v -> v % 2 != 0);
    

    请注意,如果 old Map 是 IdentityHashMap 并且 mapFactory 创建了 HashMap,则会引发重复键异常。

    【讨论】:

    • 您的 "Duplicate keys " + a + " " + b 消息具有误导性:a 和 b 实际上是值,而不是键。
    • @TagirValeev 是的,我注意到了,但这与Collectors 中toMap 的两个参数版本的操作方式相同,并将其更改为我认为会在密码框,所以我决定离开它。我现在就修改它,因为你也认为它具有误导性。
    • 是的,这是已在Java-9 中修复的已知问题(但未向后移植到 Java-8)。 Java-9 在异常消息中显示冲突键以及两个值。
    • 关于您的不安全黑客的有趣之处在于,groupingBy 收集器在幕后做了类似的事情,当您使用供应商创建执行类型安全的地图实现时,这可能会让您大吃一惊,例如()-&gt;Collections.checkedMap(new HashMap&lt;&gt;(), …)
    【解决方案6】:

    这是AbacusUtil的代码

    Map<String, String> input = N.asMap("a", "1234", "b", "2345", "c", "3456", "d", "4567");
    
    Map<String, Integer> output = Stream.of(input)
                              .groupBy(e -> e.getKey(), e -> N.asInt(e.getValue()))
                              .filter(e -> e.getValue() % 2 == 0)
                              .toMap(Map.Entry::getKey, Map.Entry::getValue);
    
    N.println(output.toString());
    

    声明:我是AbacusUtil的开发者。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 2019-11-24
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多