D
D
Davidaa_WoW2021-12-13 19:46:43
Java
Davidaa_WoW, 2021-12-13 19:46:43

How to remove all elements with the same value from hashmap?

We have a hashMap of type In the second line, the values ​​\u200b\u200bmay be repeated, how can I delete everything with the same values ​​\u200b\u200bafter adding all the elements? The hashmap would be iterated as an array, the task would be easy, but I don’t understand something. HashMap <String, String> map = new HashMap<>();

Answer the question

In order to leave comments, you need to log in

3 answer(s)
O
Odissey Nemo, 2021-12-14
@Davidaa_WoW

You create a new empty HashMap newMap - this will be the result.
You create an empty Set newSet - we will filter the values ​​through it.
From the given HashMap oldMap we get all the keys from oldMap (key) as keySet is the set of all the keys of your oldMap.
You go through oldMap using keySet, extracting values ​​(val) from oldMap one by one.
You check each value of val for its presence in newSet.
If it is present there, you have found the key to the val value duplicated in oldMap and do not save it.
If there is no val in newSet, put it there and copy the key<->val pair from oldMap to newMap;
After the end of the algorithm in newMap you have a set of only unique values.

D
Dmitry Roo, 2021-12-13
@xez

It iterates.
Methods .entrySet() .forEach((a, b) -> ...)

E
Erik Mironov, 2021-12-14
@Erik_Mironov

Use HashSet if the use of HashMap is not a prerequisite for the task.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question