Reputation: 189
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
Upvotes: 2
Views: 3397
Reputation: 383676
A TreeMap
is a SortedMap
, which sorts by keys. The way you were using it, you have String
keys, and its natural ordering is lexicographical, where "11" < "2"
.
Here's an illustration using List
to simplify:
List<String> list = new ArrayList<String>(
Arrays.asList("2", "1", "11", "b", "a", "aa")
);
Collections.sort(list);
System.out.println(list); // prints "[1, 11, 2, a, aa, b]"
Note the analogy between 1, 11, 2
and a, aa, b
. This is precisely what lexicographical ordering mandates. In a dictionary, you expect aa
to appear before b
. Similary, in this ordering, you expect 11
to appear before 2
.
If you need to compare them as Integer
, use a custom Comparator<String>
:
Comparator<String> stringAsInteger = new Comparator<String>() {
@Override public int compare(String s1, String s2) {
return Integer.valueOf(s1).compareTo(Integer.valueOf(s2));
}
};
List<String> list = new ArrayList<String>(
Arrays.asList("2", "1", "10", "007")
);
Collections.sort(list, stringAsInteger);
System.out.println(list); // prints "[1, 2, 007, 10]"
SortedMap<String, String> map = new TreeMap<String, String>(stringAsInteger);
map.put("2", "Two");
map.put("1", "One");
map.put("10", "Ten");
map.put("12", "Twelve");
map.put("7", "Seven");
System.out.println(map); // prints "{1=One, 2=Two, 7=Seven, 10=Ten, 12=Twelve}"
java.util.Comparator
Collections.sort
-- there are 2 overloadsOn Comparator
and Comparable
On sorting Map
by values
Effective Java 2nd Edition, Item 23: Don't use raw types in new code
Upvotes: 4
Reputation: 116246
I guess your problem is that keys "10" and "12" come before "2" (btw you should be more specific about your problem next time). This is simply due to the way strings are sorted.
If you want the keys to be sorted according to their integer values, you have the following options:
Integer
keys instead of String
s"01"
instead of "1"
etc.Comparator
which sorts according to your wish.Upvotes: 10
Reputation: 114757
Implement a custom Comparator and create the TreeMap with this little helper. The Comparator provides the order ("1" < "2" < "3" < ... < "10" < ... < "100").
Upvotes: 4