【问题标题】:Using Streams on a map and finding/replacing value在地图上使用 Streams 并查找/替换值
【发布时间】:2022-02-03 11:19:30
【问题描述】:

我是流的新手,我正在尝试通过此映射过滤键/值对中的第一个真值,然后我想返回字符串键,并将真值替换为假。

我有一个字符串/布尔值映射:

 Map<String, Boolean> stringMap = new HashMap<>();
 //... added values to the map

 String firstString = stringMap.stream()
        .map(e -> entrySet())
        .filter(v -> v.getValue() == true)
        .findFirst()
 //after find first i'd like to return
 //the first string Key associated with a true Value
 //and I want to replace the boolean Value with false.

这就是我卡住的地方——我可能也做错了第一部分,但我不确定如何在同一个流中返回字符串值和替换布尔值?我打算在这里尝试使用 collect 来处理返回值,但我认为如果我这样做它可能会返回一个 Set 而不是单独的字符串。

我可以使用它,但我更愿意尝试只返回字符串。我还想知道是否应该在这里使用 Optional 而不是 String firstString 局部变量。我一直在审查类似的问题,但我无法让它发挥作用,我有点迷茫。

以下是我检查过的一些类似问题,我无法在此处应用它们:

Sort map by value using lambdas and streams

Modify a map using stream

【问题讨论】:

    标签: java hashmap java-stream


    【解决方案1】:

    Map 没有stream() 方法,你的.map() 也没有任何意义。在这种情况下,entrySet() 是什么?最后,findFirst() 返回一个Optional,因此您要么更改变量,要么解开Optional

    您的代码可能如下所示:

    String first = stringMap.entrySet().stream()
        .filter(Map.Entry::getValue) // similar to: e -> e.getValue()
        .map(Map.Entry::getKey)      // similar to: e -> e.getKey()
        .findFirst()
        .orElseThrow(); // throws an exception when stringMap is empty / no element could be found with value == true
    

    还请注意,“第一个”元素在地图上下文中并没有真正意义。因为法线贴图(如HashMap)没有定义顺序(除非你使用SortedMap,如TreeMap)。

    最后,您不应该在流式传输输入映射时对其进行修改。找到“第一个”值。然后简单地做:

    stringMap.put(first, false);
    

    【讨论】:

    • 如果你没有map(Entry::getValue),你可以使用Entry.setValue()来设置找到的条目的值,而不是调用Map.put()
    • @DidierL 随时扩展这个社区维基。或者写一个新的答案;)
    【解决方案2】:
    Optional<String> firstString = stringMap.entrySet().stream()
             .filter( v-> v.getValue() == true )
             .map( e -> e.getKey())
             .findFirst();
    

    您的操作顺序似乎已取消。

    stringMap.entrySet().stream()

    在地图上,您可以流式传输键集、条目集或值集合。因此,请确保您流式传输条目集,因为您需要访问用于返回的键和用于过滤的值。

    .filter( v-&gt; v.getValue() == true )

    接下来过滤条目流,以便只保留具有真值的条目。

    .map( e -&gt; e.getKey())

    现在将条目流映射到其键的字符串值。

    .findFirst();

    找到第一个值为真的键。请注意,哈希映射中的条目没有特定的顺序。 find first 操作的结果是你已经提到的一个可选值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多