Search code examples
javaspring-bootvavr

Changing Java Map code to VAVR (javaslang)


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());
    }

  }

Solution

  • 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)
    }