Skip to content
Advertisement

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

Advertisement

Answer

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

Your ordering of the operations seems to be off.

stringMap.entrySet().stream()

On a map you could stream the key set, or the entry set, or the value collection. So make sure you stream the entry set, because you’ll need access to both the key for returning and the value for filtering.

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

Next filter the stream of entries so that only entries with a true value remain.

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

Now map the stream of entries to just the String value of their key.

.findFirst();

Find the first key whose value is true. Note that the entries in a hash map are in no particular order. The result of the find first operation is as you already mentioned an optional value.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement