Extract keys from Map for which there is no duplicate values

Vishwa Ratna :

Map is defined as:

 Map<Integer,String> map = new HashMap<>();
        map.put(2,"ram");
        map.put(3,"ram");
        map.put(4,"gopal");
        map.put(5,"madan");
        map.put(6,"shyam");
        map.put(7,"gopal");
        map.put(8,"ram");

My expected output is List which contains only keys for which there is no duplicate values.

5
6

My approach and thought process:

Thought process 1 :

I would take map.entrySet().stream().map(....) and then take another stream inside map and filter the values for which duplicate values are present.

The approach soon got wasted as the first indexed value would be again compared in the nested stream and i would happen to filter out all elements thus.

Thought process 2

I kept values in different List by :

List<String> subList = map.entrySet().stream()
        .map((k)->k.getValue())
        .collect(Collectors.toList());

and then:

    map.entrySet().stream()
            .filter(s ->
                subList.contains(s.getValue())                )
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());

But I am getting the output as

2
3
4
5
6
7
8

The output is obvious as the value that i am picking as s from stream i am comparing it in the pool where the value will be always present at-least one time.

I again thought then that if i could have a counter that count count and if the value is present then it would increment, but again all seems very much vague now.

Any ways in which i can iterate by index using stream, so that i can always leave the key value which i am taking and just comparing with rest of values.

will love to get a brief explanation.

Hadi J :

You can break the task into two step. first count value repeating by groupingBy() and counting() collectors.

Map<String,Long> valueCount = map.values()
           .stream()
           .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));

Its result is:

{madan=1, shyam=1, gopal=2, ram=3}

second step is to find only keys which their values are not duplicate. so to attain this you can use filter() and filtering the map by previous step result.

map.entrySet()
   .stream()
   .filter(entry -> valueCount.get(entry.getValue())==1).map(Map.Entry::getKey)
   .collect(Collectors.toList())

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=141004&siteId=1