Duplicate values into Map<DemoType, List<Demography>>

80 Views Asked by At

I have some problems with this piece of code.

I'm creating a Map with List of Demography but at some point I have duplicate list elements. Can you see where am I doing a mistake?

Regards.

public Map<DemoType, List<Demography>> demoTypeToDemosList(final Long campaignId, final MediaType mediaType) {
        List<MappedDemoDTO> mappedDemosList = demoTypeCampaignService.getMappedDemosByMediaTypeAndCampaignIdOrderByOrdinalRankAsc(mediaType, campaignId);

        final Set<Long> demoIds = mappedDemosList.stream().map(MappedDemoDTO::getMappedId).collect(Collectors.toSet());
        DemographyProviderService serviceByProviderAndMediaType = demographyFactory.getServiceByProviderAndMediaType(Provider.PROVIDER, mediaType);
        final List<Demo> demos = serviceByProviderAndMediaType.getDemoByExternalIds(demoIds);

        Map<DemoType, List<Demography>> demoTypeToDemosMap = new EnumMap<>(DemoType.class);

        mappedDemosList.forEach(mappedDemo -> demos.stream()
            .filter(demo -> mappedDemo.getMappedId().equals(demo.getId()))
            .findFirst()
            .ifPresent(demo -> {
                List<Demography> demosList = demoTypeToDemosMap.computeIfAbsent(mappedDemo.getDemoType(), f -> new ArrayList<>());
                demo.setId(mappedDemo.getDemoId());
                demosList.add(demo);
            }));

        return demoTypeToDemosMap;
    }
1

There are 1 best solutions below

0
Eugene On

Read the documentation of computeIfAbsent:

return the current (existing or computed) value associated with the specified key, or null if the computed value is null

This:

List<Demography> demosList = demoTypeToDemosMap.computeIfAbsent(mappedDemo.getDemoType(), f -> new ArrayList<>());

will return a new ArrayList if the key is not in the Map or the existing one, which you later simply add to it: demosList.add(demo);