Can I sort the map by key value in Java?

Asked 1 years ago, Updated 1 years ago, 132 views

<"question1", "1">, <"question9", "1">, <"question2", "4">, <"question5", "2"> I made a map that has this kind of data.

I want to arrange the key value in question 1, question 2, question 3. In conclusion, I want to get question 1 and the key value there.

Iterator it = paramMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
 questionAnswers += pairs.getKey()+",";
}

I tried it like this, but it's not aligned. What should I do?

java map hashmap

2022-09-22 22:23

1 Answers

SortedSet<String> keys = new TreeSet<String>(map.keySet());
for (String key : keys) { 
   String value = map.get(key);
   // // do something
}

Try TreeMap. TreeMap is a data structure in which maps are arranged in a tree structure according to key values.


2022-09-22 22:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.