Search code examples
javacastingjava-stream

Is it possible to use a Stream to collect an Object into a hashmap, rather than casting?


I have a map myMap of type <String, Object> which looks like:

(
"header", "a string value"
"mapObject", {object which is always of type map<String, String>}
)

I basically want to pull out the value of "mapObject" into a Map<String, String>

Initially I just cast it to an ImmutableMap like so:

(ImmutableMap<String, String>) myMap.get("mapObject");

But am wondering if there is a way to do this by making use of Stream.

I've currently got:

myMap.entrySet()
   .stream()
   .collect(Collectors.toMap(Map.Entry::getKey, entry -> (String) entry.getValue()));

But I'm getting the following exception:

class com.google.common.collect.RegularImmutableMap cannot be cast to class java.lang.String

Is there a way to do this or am I better just sticking with the cast?


Solution

  • A possible solution could look like this:

    Optional<Map<String, String>> result = myMap.entrySet()
        .stream()
        .filter(entry -> "mapObject".equals(entry.getKey()))
        .map(entry -> (Map<String, String>) entry.getValue())
        .findFirst();
    

    Your error message came from the cast of the second entry set (of type Map) to string here: entry -> (String) entry.getValue()

    Update:

    Like Holger stated the best solution nevertheless is myMap.get("mapObject"). The above solution is only to show how the problem could be solved using the Streams API.