'How to add unique entries of Map<String,Object> to List<Object> using Java Streams?

I have a List<Object> element in Java which contains Map<String, String> before adding a new Map<String, String> I would like to know if there is any Map in List already has that Key, if so do not add it. If there is no matching then add it.

I am trying to use the flatMap approach but getting a bit confused halfway through and unable to find an efficient approach. Hence, Looking for some suggestions on efficient and less processing approaches.

Also, if I am doing the check on the empty list then it's failing as well and not adding the values. I would like to do the check for the key before adding every map if not present then add it, if present skip it.

Following is the code I have so far:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        List<Object> list = new ArrayList<>();
        list.add("String Element");

        Map<String, String> map1 = new HashMap<>();
        map1.put("key1", "value1");
        list.add(map1);

        Map<String, String> map2 = new HashMap<>();
        map2.put("key2", "value2");
        list.add(map2);

        Map<String, String> map3 = new HashMap<>();
        map3.put("key3", "value3");
        list.add(map3);

        System.out.println("Before Duplicate Addition : " + list);
        Map<String,String> dupChecker = list.stream().filter(c -> c instanceof Map<?, ?>).map(c -> (Map<String, String>) c).flatMap(m -> m.entrySet().stream()).collect(Collectors.toMap(en->en.getKey(), en-> en.getValue(), (r1, r2) -> r1));
        
    }
}


Solution 1:[1]

You have to split the problem into 3 steps:

  • collect the entries (groupsByKey)
  • group by key and get the number of entries per key (groupsByKey)
  • filter the entries having a count equal to 1 (finalResult)
List<Map.Entry<String, String>> entries = list.stream()
        .filter(c -> c instanceof Map<?, ?>)
        .map(c -> (Map<String, String>) c)
        .flatMap(m -> m.entrySet().stream())
        .toList();

Map<String, Long> groupsByKey = entries.stream()
        .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.counting()));

Map<String, String> finalResult = entries.stream()
        .filter(e -> groupsByKey.get(e.getKey()) == 1)
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

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 frascu