简体   繁体   中英

Map Keys sorting based on numbers and character

[result][1]    
package info.sreenu.collectionsmap;
import java.util.HashMap;
import java.util.Map;
public class MapDemo {
public static void main(String[] args) {
Map m=new HashMap();
m.put(1,"satya");
m.put('a',"anil");
m.put('b',"raju");
m.put('c',"nayana");
m.put(2,"hiyathi");
System.out.println(m.keySet());
System.out.println(m.values());
}
}

Here I need to sort the map keys based on numbers and based on characters.

Change the code to use TreeMap instead of HashMap. That's sorts the data based on key.

Here's a better explanation of the same.

Secondly, you cannot insert both Integer and Character as a key because they cannot be casted.
You can either write a comparator or convert all keys (Integer,Characters) to String and insert that as Key.

Map m=new TreeMap();
m.put(String.valueOf(1),"satya");
m.put(String.valueOf('a'),"anil");
m.put(String.valueOf('b'),"raju");
m.put(String.valueOf('c'),"nayana");
m.put(String.valueOf(2),"hiyathi");
System.out.println(m.keySet());
System.out.println(m.values());

Refer to this on how to use comparators with TreeMap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM