在地图上使用流和 finding/replacing 值

Using Streams on a map and finding/replacing value

我是流的新手,我正在尝试通过此映射过滤 key/value 对中的第一个真值,然后我想 return 字符串键,并替换true 与 false 的值。

我有一张 strings/booleans 的地图:

 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.

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

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

以下是我查过的一些类似问题,我不能在这里应用它们:

Modify a map using stream

Map 没有 stream() 方法,您的 .map() 也没有任何意义。在这种情况下 entrySet() 是什么?最后,findFirst() returns 一个 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

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

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

stringMap.put(first, false);
Optional<String> firstString = stringMap.entrySet().stream()
         .filter( v-> v.getValue() == true )
         .map( e -> e.getKey())
         .findFirst();

您的操作顺序似乎有误。

stringMap.entrySet().stream()

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

.filter( v-> v.getValue() == true )

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

.map( e -> e.getKey())

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

.findFirst();

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