'Using Streams on a map and finding/replacing value

I'm new to streams and I am trying to filter through this map for the first true value in a key/value pair, then I want to return the string Key, and replace the Value of true with false.

I have a map of 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.

That is where I am stuck--I might be doing the first part wrong too, but I'm not sure how to both return the string value and replace the boolean value in the same stream? I was going to try to use collect here to deal with the return value, but I think if I did that it would maybe return a Set rather than the string alone.

I could work with that but I would prefer to try to just return the string. I also wondered if I should use Optional here instead of the String firstString local variable. I've been reviewing similar questions but I can't get this to work and I'm a bit lost.

Here are some of the similar questions I've checked by I can't apply them here:

Sort map by value using lambdas and streams

Modify a map using stream



Solution 1:[1]

Map doesn't have a stream() method, also your .map() doesn't really make sense. What is entrySet() in that context? And at last, findFirst() returns an Optional so you'd either change the variable, or unwrap the Optional.

Your code could look something like this:

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

Please also note that the "first" element doesn't really make sense in the context of maps. Because a normal map (like HashMap) has no defined order (unless you use SortedMap like TreeMap).

At last, you shouldn't modify the input map while streaming over it. Find the "first" value. And then simply do:

stringMap.put(first, false);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1