'Collecting a basic map in Java 8 streams API

    Map<String, String> preFilteredKafkaRecords = kafkaRecordMap.entrySet().stream()
            .map(item -> getUrls(item.getKey(), item.getValue()))
            .filter(THING_1)
            .filter(THING_2)
            .collect(Collectors.toMap(
                    Map.Entry<String, String>::getKey, Map.Entry<String, String>::getValue));

getUrls - returns Map<String, String>

how can I collect this to a Map<String, String>? The first map returns a Map<String, String> but I can't get the compiler to stop complaining.



Solution 1:[1]

If getUrls() returns a Map, you can't collect it as an Entry. If the idea is to combine all the maps, you can use flatMap() to merge their entries into one stream:

Map<String, String> preFilteredKafkaRecords = kafkaRecordMap.entrySet().stream()
    .map(item -> getUrls(item.getKey(), item.getValue()))
    .map(Map::entrySet)
    .flatMap(Set::stream)
    .filter(THING_1)
    .filter(THING_2)
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Alternatively, you can use a custom collector to fold each result into a single map:

Map<String, String> preFilteredKafkaRecords = kafkaRecordMap.entrySet().stream()
    .map(item -> getUrls(item.getKey(), item.getValue()))
    .filter(THING_1)
    .filter(THING_2)
    .collect(HashMap::new, Map::putAll, Map::putAll);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 shmosel