How to Sort Map Values by Key in Java?
I Have a Map That Has Strings for Both Keys and Values. Data Is Like Following: "Question1", "1" "Question9", "1" "Question2", "4" "Question5", "2" I Want to...
I have a Map that has strings for both keys and values.
Data is like following:
"question1", "1"
"question9", "1"
"question2", "4"
"question5", "2"
I want to sort the map based on its keys. So, in the end, I will have question1, question2, question3....and so on.
Eventually, I am trying to get two strings out of this Map.
- First String: Questions ( in order 1 ..10)
- Second String: Answers (in the same order as the question)
Right now I have the following:
Iterator it = paramMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
questionAnswers += pairs.getKey() + ",";
}
This gets me the questions in a string but they are not in order.
17 Answers
Must Read
Short answer
Use a TreeMap. This is precisely what it's for.
If this map is passed to you and you cannot determine the type, then you can do the following:
SortedSet<String> keys = new TreeSet<>(map.keySet());
for (String key : keys) {
String value = map.get(key);
// do something
}
This will iterate across the map in natural order of the keys.