---
title: "swap keys and duplicate values in hashmap"  
description: "swap keys and duplicate values in hashmap"  
author: "Anonymous User"  
published: 2015-04-22  
updated: 2015-04-22  
canonical: https://www.mindstick.com/forum/23111/swap-keys-and-duplicate-values-in-hashmap  
category: "java"  
tags: ["java"]  
reading_time: 1 minute  

---

# swap keys and duplicate values in hashmap

Hey Everyone,I have interesting [question](https://www.mindstick.com/blog/23175/how-to-solve-neet-question-paper-in-less-time) on [hash](https://www.mindstick.com/forum/159584/what-are-the-differences-between-a-hashmap-and-a-hash-table-in-c-sharp) [map](https://yourviews.mindstick.com/view/81351/nepal-parliament-s-approves-new-controversial-map-india-rejects-it-but) and it says : \
I have a hash map with [values](https://www.mindstick.com/forum/327/sum-textbox-values) : {"1-a","2-a","3-b","4-b"} [Keys](https://www.mindstick.com/articles/75385/full-product-keys) Values 1 a 2 a 3 b 4 b \
I need to [swap](https://www.mindstick.com/forum/34027/how-to-swap-the-values-of-two-columns-in-sql-server) the key values with losing the [data](https://www.mindstick.com/articles/13050/salesforce-aiming-to-dominate-predictive-analytics-with-data-science) , means the new hash map should be : Keys Values a 1,2 b 3,4 \
Can [anyone](https://www.mindstick.com/articles/23207/how-to-find-the-best-fit-job-for-anyone) [suggest me](https://www.mindstick.com/interview/23114/can-you-suggest-me-few-top-directory-submission-site) the way to do this?

## Replies

### Reply by Anonymous User

Finally after a lot of research i have done it

```
Map<String, Set<String> > newmap = new HashMap<String, Set<String> >(); map.put("1", "a"); map.put("2", "a"); map.put("3", "b"); map.put("4", "b"); System.out.println("before Reversing"); for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("The key ::"+entry.getKey()+":: The value"+entry.getValue()); } for (Map.Entry<String, String> entry : map.entrySet()) { String oldVal = entry.getValue(); String oldKey = entry.getKey(); Set<String> newVal = null; if (newmap.containsKey(oldVal)) { newVal = newmap.get(oldVal); newVal.add(oldKey); } else { newVal= new HashSet<>(); newVal.add(oldKey); } newmap.put(oldVal, newVal); } System.out.println("After Reversing"); for (Map.Entry<String, Set<String>> entry : newmap.entrySet()) { System.out.print("The key ::"+entry.getKey()+":: The value"+entry.getValue()); } } }
```


---

Original Source: https://www.mindstick.com/forum/23111/swap-keys-and-duplicate-values-in-hashmap

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
