John Lippson
John Lippson

Reputation: 1319

Converting values in Map to List<Serializable> in Java 8

I have a TreeMap that contains <String, Object>. I'm looking to convert the values in the TreeMap to a List<Serializable> that contains a special value.

My Attempt

  private List<Serializable> getSecurityAttributes(
      Map<String, Object> inputTemplate, String securityAccess) {
    return inputTemplate
        .entrySet()
        .stream()
        .filter(obj -> obj.getKey().contains(securityAccess))
        .map(Map.Entry::getValue)
        .map(Serializable.class::cast)
        .collect(Collectors.toList());
  }

I'm getting a class cast exception and not quite sure why.

Specific Error:

Cannot cast org.boon.core.value.ValueList to java.io.Serializable

Upvotes: 0

Views: 1032

Answers (2)

John Lippson
John Lippson

Reputation: 1319

I casted the ValueList to a regular List and ran flatMap on it to cast each of the values.

  private List<Serializable> getSecurityAttributes(
      Map<String, Object> inputTemplate, String securityAccess) {
    return inputTemplate
        .entrySet()
        .stream()
        .filter(obj -> obj.getKey().contains(securityAccess))
        .map(Map.Entry::getValue)
        .map(List.class::cast)
        .flatMap(List::stream)
        .map(Object::toString)
        .collect(Collectors.toList());
  }

Upvotes: 1

Oli
Oli

Reputation: 10406

An Ojbect cannot necessarily be cast to a String (do not confuse calling toString() on an object, which is always possible and casting to a String which requires the object to be a subtype of String). For instance, running this: System.out.println(String.class.cast(new Object())); yields:

Exception in thread "main" java.lang.ClassCastException: Cannot cast java.lang.Object to java.lang.String
    at java.lang.Class.cast(Class.java:3369)
    at p493.Run493.main(Run493.java:42)

But System.out.println(new Object().toString()); yields java.lang.Object@2a139a55.

I do not know what you are trying to do exactly but your code would run if you replace .map(String.class::cast) by .map(Object::toString).

Upvotes: 0

Related Questions