QWERTY
QWERTY

Reputation: 13

sorting of HashMap in Java

I have a Map, with keys and values in it

Keys:- case 1, case 2......case 10

Values:- Jan, Feb......Oct

Now when i put this map in array list (so that i can sort it)

for (String key : dataValueMap.keySet()) {
    System.out.println(key + " " + dataValueMap.get(key));
}
ArrayList<String> keys = new ArrayList<String>(
dataValueMap.keySet());
Collections.sort(keys);
for (String counter : keys) {
   System.out.println(counter); >>>>>BUT it prints like :- case 1  then  case 10  then  case 2, case 3, case 4 etc.
}

Kindly help in fixing this issue,

Thanks in advance

Upvotes: 1

Views: 92

Answers (3)

Raman Sahasi
Raman Sahasi

Reputation: 31841

Well you just have to define a new custom Comparator for your version of string and can write any logic that will compare two Strings from the list.

List<String> keys = new ArrayList<>();

keys.add("case 10");    
keys.add("case 3");        
keys.add("case 1");
keys.add("case 2");

Comparator<String> comparator = new Comparator<String>(){
    @Override
    public int compare(String s1, String s2) {
        return Integer.compare(Integer.parseInt(s1.substring(5)), Integer.parseInt(s2.substring(5)));
    }  
};

Collections.sort(keys, comparator);
for (String counter : keys) {
    System.out.println(counter);
}

Upvotes: 0

Darshan Mehta
Darshan Mehta

Reputation: 30809

If you are certain about the key format then you can split it by space and compare the actual value with comparator, e.g.:

Map<String, Object> myMap = 
        new TreeMap<String, Object>(new Comparator<String>()
        {
            public int compare(String o1, String o2)
            {
                Integer value1 = Integer.parseInt(o1.split("\\s+")[1]);
                Integer value2 = Integer.parseInt(o2.split("\\s+")[1]);
                return value1.compareTo(value2);
            } 
});

Although it would break if the key format is not correct, we can add the handling for that depending upon the expected behavior.

Upvotes: 1

d.j.brown
d.j.brown

Reputation: 1842

Use a custom Comparator implementation to sort your collection. This takes and compares the integers of the key, but is reliant on the format case n

Example

List<String> keys = new ArrayList<>();
keys.add("case 10");        
keys.add("case 3");        
keys.add("case 1");
keys.add("case 2");        
Collections.sort(keys, new Comparator<String>() {

    @Override
    public int compare(String s1, String s2) {
        s1 = s1.split(" ")[1];
        s2 = s2.split(" ")[1];
        return Integer.compare(Integer.parseInt(s1), Integer.parseInt(s2));
    }
});

for (String key : keys) {
    System.out.println(key);
}

Upvotes: 3

Related Questions