I was writing a code using HashMap | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I was writing a code using HashMap

How do i remove duplicate values from the HashMap https://code.sololearn.com/cDntWvZ688b5/?ref=app

17th Aug 2020, 1:09 PM
stephen haokip
stephen haokip - avatar
2 Answers
+ 3
Do you care what key is removed when it maps to a duplicated value? If no, the following method should work. Note that the result is returned so you'll have to assign that to a variable. private static HashMap<String, String> removeDuplicateValues(Map<String, String> map) { HashSet<String> values = new HashSet<String>(); HashMap<String, String> result = new HashMap<String, String>(); for (Map.Entry<String, String> pair: map.entrySet()) { if (!values.contains(pair.getValue())) { result.put(pair.getKey(), pair.getValue()); values.add(pair.getValue()); } } return result; } I used HashSet which you can import or replace all your imports with import java.util.*; I tested that with a main like this: public static void main(String[] args){ HashMap<String, String> map = createMap(); map = removeDuplicateValues(map); for (Map.Entry<String, String> pair : map.entrySet()){ System.out.println(pair.getKey() + ": " + pair.getValue()); } } The output was: haokip8: stephen3 haokip9: stephen4 haokip4: stephen7 haokip5: stephen6 haokip6: stephen5 haokip0: stephen2 haokip1: stephen0 haokip2: stephen9 haokip3: stephen8 Notice that stephen4 appears only once. createMap adds 2 stephen4 values. PS: Fix your indentation. It looks really bad in Sololearn's Code Editor.
17th Aug 2020, 6:02 PM
Josh Greig
Josh Greig - avatar
0
Thank you Josh Greig
18th Aug 2020, 2:51 AM
stephen haokip
stephen haokip - avatar