Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a hashmap with some keys pointing to same values. I want to find all the values that are equal and print the corresponding keys.

This is the current code that I have:

    Map<String, String> map = new HashMap<>();

    map.put("hello", "0123");
    map.put("hola", "0123");
    map.put("kosta", "0123");
    map.put("da", "03");
    map.put("notda", "013");

    map.put("twins2", "01");
    map.put("twins22", "01");


    List<String> myList = new ArrayList<>();

    for (Map.Entry<String, String> entry : map.entrySet()) {
       for (Map.Entry<String, String> entry2 : map.entrySet()){
           if (entry.getValue().equals(entry2.getValue()))
           {
               myList.add(entry.getKey());
           }
       }

    }

The current code adds the duplicates two times into the list, however it also adds every key one time.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
721 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use streams to retrive duplicates in this way:

  List<String> myList = map.stream()
     .filter(n -> Collections.frequency(map.values(), n) > 1)
     .collect(Collectors.toList());

And then, you can print this out with:

myList.foreach(System.out::println);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...