How to convert Map<String, String> to Map<MyClass, MyOtherClass>?

I have a simple Map<String, String> scanMap and I want to collect and covert it to a map of type of Map<CustomTag, CustomTagType>.

CustomTag has 2 fields properties – key & value and I want to inject the original map key & value into it. the 2nd CustomTagType is an enum.
I want to do something like this:

Map<String, String> scanMap = new HashMap<>();
scanMap.entrySet()
        .stream()
        .collect(Collectors.toMap(e -> CustomTag.builder().key(e.getKey()).value(e.getValue()).build(),
                        CustomTagType.SCAN_TAG);

but the e.getKey() & e.getValue() get ‘cannot resolve method’ errors.
What am I missing here?

>Solution :

Both arguments to Collectors.toMap must be Functions (which are passed an element of the Stream), even if their parameter is unused.

Collectors.toMap(e -> CustomTag.builder().key(e.getKey()).value(e.getValue()).build(),
                 e -> CustomTagType.SCAN_TAG)

Leave a Reply