Reputation: 155
I have a map of string to String, and I want to sort the maps based on thier value for the kay F
, but my code fails doing so. please advise.
Map<String, String> h = null;
Map<String, String> h1 = null;
Map<String, String> h2 = null;
listSummaryMap = new ArrayList<Map<String, String>>();
h = new HashMap<String, String>();
h.put("SUCCESS", "27");
h.put("TOTAL_HOTELS", "86");
h.put("F", "86");
h.put("RESERVATION_MODE", "86");
h.put("PARTNER_NAME", "86");
h1 = new HashMap<String, String>();
h1.put("SUCCESS", "27");
h1.put("TOTAL_HOTELS", "86");
h1.put("F", "36");
h1.put("RESERVATION_MODE", "86");
h1.put("PARTNER_NAME", "86");
h2 = new HashMap<String, String>();
h2.put("SUCCESS", "27");
h2.put("TOTAL_HOTELS", "86");
h2.put("F", "28");
h2.put("RESERVATION_MODE", "86");
h2.put("PARTNER_NAME", "86");
listSummaryMap .add(h);
listSummaryMap .add(h1);
listSummaryMap .add(h2);
Collections.sort(listSummaryMap , new Comparator<Map<String, String>>() {
@Override
public int compare(Map<String, String> o1, Map<String, String> o2) {
return o2.get("F").compareTo(o1.get("F"));
}
});
Upvotes: 1
Views: 79
Reputation: 1538
You forgot to add the maps to your list and the map h3 is never initialized. That taken apart your code already works as is but sorts the maps from the highest id to the lowest. If you change your comparison line to that:
Collections.sort(listSummaryMap , new Comparator<Map<String, String>>() {
@Override
public int compare(Map<String, String> o1, Map<String, String> o2) {
return o1.get("F").compareTo(o2.get("F"));
}
});
Then it will sort your maps by "F" from the lowest to the highest value.
Hope it helps
Upvotes: 0
Reputation: 3507
Need to convert String to integer first and then compare will work like this.
Collections.sort(listSummaryMap , new Comparator<Map<String, String>>() {
@Override
public int compare(Map<String, String> o1, Map<String, String> o2) {
Integer a=Integer.parseInt(o2.get("F"));
Integer b=Integer.parseInt(o1.get("F"));
return b.compareTo(a);
}
});
Upvotes: 0
Reputation: 393846
Convert the String
s to Integer
s and compare as Integer
s :
public int compare(Map<String, String> o1, Map<String, String> o2) {
return Integer.valueOf(o2.get("F")).compareTo(Integer.valueOf(o1.get("F")));
}
This is assuming the "F"
key is always present in the Map
s, and its value can always be parsed to an Integer
.
BTW, I don't see where you add the Map
s to listSummaryMap
. Did you forget to include that code in your question?
Upvotes: 2