Ryan
Ryan

Reputation: 1242

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.

Upvotes: 0

Views: 184

Answers (1)

shmosel
shmosel

Reputation: 50766

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

Upvotes: 3

Related Questions