-1

I have 2 methods involving Map in plain Java and my task is to change them to full VAVR. The problem for now is that I get

java.lang.ClassCastException: class java.util.HashMap cannot be cast to class io.vavr.collection.Map (java.util.HashMap is in module java.base of loader 'bootstrap'; io.vavr.collection.Map is in unnamed module of loader 'app')

I think that I know where the problem is but as a beginner I just can't build that code in full VAVR. I know that this kind of questions are not welcome on stackoverflow but there is limited amount of materials about VAVR on the web and I simply can't find any example that could help me. I am kindly asking for any help - code snippet, suggestions where to find similar example or anything that could help me. I have read manual on VAVR webpage and many tutorials but still could not build my methods. Hope you will understand, I am not proud of that topic.

public io.vavr.collection.Map<Object, Object> flatten(final Map<Field, Option<Object>> data) {
    final Map<Object, Object> result = new HashMap<>();
    for (final Map.Entry<Field, Option<Object>> entry : data.entrySet()) {
      if (entry.getValue().isDefined()) {
        result.put(flattenKey(entry), flatten(entry.getValue()));
      }
    }
    return (io.vavr.collection.Map<Object, Object>) result;
  }


private Object flattenKey(final Map.Entry<?, ?> entry) {
    if (entry.getKey() == null || StringUtils.isEmpty(String.valueOf(entry.getKey()))) {
      return IndexerHelper.EMPTY_FIELD_NAME;
    } else {
      return flatten(entry.getKey());
    }

  }
wojciechw
  • 71
  • 1
  • 13
  • 2
    Well, why are you using `java.util.HashMap` at all? Use `io.vavr.collection.HashMap`, there won't be need for that casting at return from function. – user158037 Aug 23 '19 at 13:58

1 Answers1

0

How about something like this? Using only vavr Map

public Map<Object, Object> flatten(Map<Field, Option<Object>> data) {
    return data.filterValues(Option::isDefined)
               .bimap(this::someFlattenOnKey, this::someFlattenOnValue)
}

And if you absolutely need to get a Java Map as input:

public io.vavr.collection.Map<Object, Object> flatten(Map<Field, Option<Object>> data) {
    return io.vavr.collection.HashMap.ofAll(data)
               .filterValues(Option::isDefined)
               .bimap(this::someFlattenOnKey, this::someFlattenOnValue)
}
Sir4ur0n
  • 1,753
  • 1
  • 13
  • 24
  • 1
    Generics are doing you no good here. Map? No better than Map interface without generics. – duffymo Aug 26 '19 at 18:17
  • 2
    Totally irrelevant. OP doesn't mention anything about the key/value types. His question is about converting a Java Map to a Vavr Map, and transforming keys and values in the process. And Map carries more info than Map, so it's still a win. – Sir4ur0n Aug 27 '19 at 19:41