RqndomHax
RqndomHax

Reputation: 15

Java cannot cast HashMapNode

I have tried something like this to get an HashMap<String, String> from an HashMap<String, Object> (containing only Strings)

(getObjects() returns this HashMap<String, Object>)

public <V> Map<String, V> castObjects(final Class<V> cast) {
    return getObjects().entrySet().stream()
            .filter(entry -> cast.isInstance(entry.getValue()))
            .collect(Collectors.toMap(Map.Entry::getKey, cast::cast));
}

HashMap<String, String> strings = (HashMap<String, String>) castObjects(String.class)

But I get the following error:

java.lang.ClassCastException: Cannot cast java.util.HashMap$Node to java.lang.String

Do you guys have any idea where my castObjects method is wrong ?

Upvotes: 1

Views: 236

Answers (1)

matt
matt

Reputation: 12347

Your second argument to toMap needs to extract the value and cast.

entry -> cast.cast( entry.getValue())

Right now you're trying to cast the entry hence you get the error.

When I tried I didn't get an exception.

public static void main (String[] args) throws java.lang.Exception
{
    Map<String, Object> org = new HashMap<>();
    org.put("one", "two");
    
    org.entrySet().stream()
        .filter(entry -> String.class.isInstance(entry.getValue()))
        .collect(
            Collectors.toMap(
                Map.Entry::getKey, 
                entry -> String.class.cast(entry.getValue())
                ));
}

Upvotes: 1

Related Questions