I have an ArrayList
of HashMap
. Each HashMap
contains many key-value-pairs. I want to sort the ArrayList
by the value of the key distance
in the HashMap
.
ArrayList<HashMap<String, String>> arrayListHashMap =
new ArrayList<HashMap<String, String>>();
{
HashMap hashMap = new HashMap<String, Object>();
hashMap.put("key", "A key");
hashMap.put("value", "B value");
hashMap.put("distance", 2536);
arrayListHashMap.add(hashMap);
}
{
HashMap hashMap = new HashMap<String, String>();
hashMap.put("key", "B key");
hashMap.put("value", "A value");
hashMap.put("distance", 2539);
arrayListHashMap.add(hashMap);
}
Add all the HashMap
s to a list and sort it using a custom Comparator
like this:
Collections.sort(arrayListHashMap, new Comparator<HashMap<String, Object>>() {
@Override
public int compare(HashMap<String, Object> o1, HashMap<String, Object> o2) {
return ((Integer) o1.get("distance")).compareTo(
(Integer) o2.get("distance"));
}
});
Full example:
public static void main(String... args) {
List<HashMap<String, Object>> arrayListHashMap =
new ArrayList<HashMap<String, Object>>();
{
HashMap<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("key", "A key");
hashMap.put("value", "B value");
hashMap.put("distance", 2536);
arrayListHashMap.add(hashMap);
}
{
HashMap<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("key", "B key");
hashMap.put("value", "A value");
hashMap.put("distance", 2539);
arrayListHashMap.add(hashMap);
}
Collections.sort(arrayListHashMap,
new Comparator<HashMap<String, Object>>() {
@Override
public int compare(
HashMap<String, Object> o1,
HashMap<String, Object> o2) {
return ((Integer) o1.get("distance")).compareTo(
(Integer) o2.get("distance"));
}
});
System.out.println(arrayListHashMap);
}
You can try to sort with a custom comparator:
Collections.sort(arrayListHashMap, new Comparator<HashMap<String, String>>() {
@Override
public int compare(HashMap<String, String> m1, HashMap<String, String> m2) {
return Integer.valueOf(m1.get("distance")).compareTo(Integer.valueOf(m2.get("distance")));
}
});
Note that I assumed all your values are strings which is not the case in your example (distance is an int value).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With