问题
I have map like
Map<String,Integer> mp = new TreeMap<>();
mp.put("R1", 00);
mp.put("R0", 11);
mp.put("R2", 22);
mp.put("R3", 33);
mp.put("R5", 55);
mp.put("R8", 88);
mp.put("R4", 44);
mp.put("R6", 66);
mp.put("R9", 99);
mp.put("R7", 77);
mp.put("R11", 1111);
mp.put("R14", 1414);
mp.put("R10", 1010);
mp.put("R12", 1212);
mp.put("R13", 1313);
mp.put("R15", 1515);
mp.put("R17", 1717);
mp.put("R19", 1919);
I want to sort based upon keys. TreeMap is not working because of alphanumeric, getting output
{R0=11, R1=0, R10=1010, R11=1111, R12=1212, R13=1313, R14=1414, R15=1515, R17=1717, R19=1919, R2=22, R3=33, R4=44, R5=55, R6=66, R7=77, R8=88, R9=99}
Suggest how to do this?
回答1:
Create and pass to your TreeMap Comparator which will compare only integer part from keys (assuming that all keys are in form of R[number]
).
In Java 8 your map can look like
Map<String, Integer> mp = new TreeMap<>(
Comparator.comparingInt(key -> Integer.parseInt(key.substring(1))));
In Java 7 you can use rewrite it as
Map<String, Integer> mp = new TreeMap<>(new Comparator<String>(){
@Override
public int compare(String key1, String key2) {
//parse only text after first letter
int k1 = Integer.parseInt(key1.substring(1));
int k2 = Integer.parseInt(key2.substring(1));
return Integer.compare(k1, k2);
}
});
It will order elements in a way:
{R0=11, R1=0, R2=22, R3=33, R4=44, R5=55, R6=66, R7=77, R8=88, R9=99, R10=1010, R11=1111, R12=1212, R13=1313, R14=1414, R15=1515, R17=1717, R19=1919}
回答2:
You can create an Set
of Entry
object from the Map
. Then pass a custom Comparator
to the Collections.sort()
along with the Set
. I have give the template below.
Set<Entry<String, Integer>> set = map.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
Collections.sort( list, new Comparator<Map.Entry<String, Integer>>()
{
public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 )
{
// Put your logic here for sorting.
}
} );
You can use the regex
or substring
method from String
for separating the chars and numbers from the String
.
来源:https://stackoverflow.com/questions/32769266/how-to-sort-alphanumeric-keys-in-hashmap-in-best-possible-manner