bond
bond

Reputation: 718

Sorting HashMap<String, String> with integers as Strings

I'm trying to sort my HasMap ArrayList so my listview is sorted by values but I'm not getting it. Basically I have several keys and one of them is "type" which holds values like "1", "4", "3",....

I want to order the list by this key "type" but I'm getting "1", "11", "2" instead of "1", "2", "11"...

I'm trying this code to sort it:

Collections.sort(myList, new Comparator<HashMap<String, String>>() {
public int compare(HashMap<String, 
String> mapping1,HashMap<String, String> mapping2) {
return mapping1.get("type").compareTo(mapping2.get("type"));
    }
});

Upvotes: 0

Views: 2215

Answers (4)

RUTURAJ Raval
RUTURAJ Raval

Reputation: 133

You can do as below..

Change parameter as per your need..

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 )
            {
                return (o2.getValue()).compareTo( o1.getValue() );
            }
        } );
        for(Map.Entry<String, Integer> entry:list){
            System.out.println(entry.getKey()+" ==== "+entry.getValue());
        }

Upvotes: 0

anotherdave
anotherdave

Reputation: 6754

You'll need to handle non-integer values in your comparator, if, as you mentioned above, you expect to have a mixture of String and Integer keys.

Collections.sort(myList, new Comparator<HashMap<String, String>>() {
    public int compare(HashMap<String, String> mapping1,
                       HashMap<String, String> mapping2) {
        String valueOne = mapping1.get("type");
        String valueTwo = mapping2.get("type");
        try {
            return Integer.valueOf(valueOne).compareTo(Integer.valueOf(valueTwo));
        } catch(NumberFormatException e) {
            return valueOne.compareTo(valueTwo);
        }
    }
});

(Otherwise, the key value should be changed to Integer to avoid mistakes by other developers.)

Upvotes: 0

Santosh
Santosh

Reputation: 17893

Your type is a String and thats why you are getting "1", "11", "2". Convert that string to integer (Integer.valueOf()) and then compare.

change the following

mapping1.get("type").compareTo(mapping2.get("type"));

to

 Integer.valueOf(mapping1.get("type")).compareTo(Integer.valueOf(mapping2.get("type")));

Note: I did not compile the above code.

Upvotes: 5

sanbhat
sanbhat

Reputation: 17622

The data-type of "type" seems to be String. Hence the sorting "1", "11", "2" seems correct. Change the data-type of "type" to Integer

OR

in compare method compare Integer.parseInt values of the "type"

Upvotes: 1

Related Questions