Search code examples
javalambdajava-8

How to filter key-value pair from a map , if there is no duplicate values using lambda


I have a following map:

Map<String, String> date = new HashMap();
date.put("2021-03-24",  "2021-03-26");
date.put("2021-03-03",  "2021-03-03");
date.put("2021-03-01",  "2021-03-03");
date.put("2021-03-25",  "2021-03-25");
date.put("2021-03-02",  "2021-03-03");
date.put("2021-03-01",  "2021-03-01");
date.put("2021-03-04",  "2021-03-04");

My requirement is to filter out the key value pairs, which have duplicate values, so the remaining key value pairs in the output should be as below:

2021-03-24= 2021-03-26,
2021-03-25= 2021-03-25,
2021-03-01= 2021-03-01,
2021-03-04= 2021-03-04,

I have used below lambda:

 Set<String> uniqueSet = date.values().stream()
                    .collect(Collectors.toMap(Function.identity(), v -> true, (a,b) -> false))
                    .entrySet().stream()
                    .filter(Map.Entry::getValue)
                    .map((Map.Entry::getKey))
                    .collect(Collectors.toSet());

But I don't want the result as a Set. I want the result as a Map.


Solution

  • Try this.

    Map<String, String> result = date.entrySet().stream()
        .collect(Collectors.groupingBy(e -> e.getValue()))
        .values().stream()
        .filter(list -> list.size() == 1)
        .map(list -> list.get(0))
        .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
    for (Entry<String, String> e : result.entrySet())
        System.out.println(e);
    

    output:

    2021-03-04=2021-03-04
    2021-03-25=2021-03-25
    2021-03-24=2021-03-26
    2021-03-01=2021-03-01