How to sort Map in Java
Posted
by kalpesh
on Stack Overflow
See other posts from Stack Overflow
or by kalpesh
Published on 2010-05-25T09:39:35Z
Indexed on
2010/05/25
9:51 UTC
Read the original article
Hit count: 318
java
hi i want to sort map according to its key value plz see code below
public static void main(String[] args) {
SortedMap map = new TreeMap();
// Add some elements:
map.put("2", "Two");
map.put("1", "One");
map.put("5", "Five");
map.put("4", "Four");
map.put("3", "Three");
map.put("10", "Ten");
map.put("12", "Twelve");
map.put("7", "Seven");
map.put("9", "Nine");
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
Object key = iterator.next();
System.out.println("key : " + key + " value :" + map.get(key));
}
}
Result Should come below
key : 1 value :One
key : 2 value :Two
key : 3 value :Three
key : 4 value :Four
key : 5 value :Five
key : 7 value :Seven
key : 9 value :Nine
key : 10 value :Ten
key : 12 value :Twelve
© Stack Overflow or respective owner