Reputation: 3407
I have a List of List. I want to sort the Super List depends on the sub list size. The Lists are dynamic.
The List type is <ArrayList<ArrayList<HashMap>>>
Eg.
[ [{key1=value1,key2=value2}],[],[{key1=value1}],[{key1=value1},{key2=value2},{key3=value3}] ]
After The sorting it should display
[[{key1=value1},{key2=value2},{key3=value3}], [{key1=value1,key2=value2}],[{key1=value1}],[] ]
Can you help how to sort this?
Thanks in advance.
Laxman chowdary
Upvotes: 3
Views: 2962
Reputation: 20065
EDITED :
If you want to sort a List of List of Map ordered by List of Map size you can do this.
Note that you can change the order of parameters (o1
and o2
) in Integer.valueOf(o1.size()).compareTo(o2.size())
to sort in the decreasing order.
public static <T> List<? extends List<T>> sortListByValue(List<? extends List<T>> list) {
Collections.sort(list, new Comparator<List<T>>() {
@Override
public int compare(List<T> o1, List<T> o2) {
//return Integer.compare(o1.size(), o2.size()); //JDK7
//Use this if you're using a version prior to 1.7.
return Integer.valueOf(o1.size()).compareTo(o2.size());
}
});
return list;
}
public static void main(String[] args) {
ArrayList<Map<String,String>> list1 = new ArrayList<>();
list1.add(new HashMap<String, String>(){{ put("1", "a"); put("2", "b");}});
list1.add(new HashMap<String, String>(){{ put("1", "a"); put("2", "b"); put("3", "c");}});
list1.add(new HashMap<String, String>(){{ put("1", "a"); }});
ArrayList<Map<String,String>> list2 = new ArrayList<>();
list2.add(new HashMap<String, String>(){{ put("1", "a"); put("2", "b");}});
list2.add(new HashMap<String, String>(){{ put("1", "a"); put("2", "b"); put("3", "c");}});
ArrayList<Map<String,String>> list3 = new ArrayList<>();
list3.add(new HashMap<String, String>(){{ put("1", "a"); put("2", "b");}});
ArrayList<ArrayList<Map<String,String>>> list = new ArrayList<>();
list.add(list1);
list.add(list2);
list.add(list3);
System.out.println(list);
System.out.println(sortListByValue(list));
}
Upvotes: 6
Reputation: 14549
public static <T> List<List<T>> sortBySublistSize(List<List<T>> superList) {
Collections.sort(superList, new Comparator<List<T>>() {
@Override
public int compare(List<T> o1, List<T> o2) {
return Integer.compare(o1.size(), o2.size());
}
});
return superList;
}
Upvotes: 1
Reputation: 5735
Collections.sort(list, new Comparator<List<? extends Map>>() {
public int compare(List<? extends Map> list1, List<? extends Map> list2) {
return Integer.valueOf(list1.size()).compareTo(Integer.valueOf(list2.size()));
}
});
If you do not take care about generics that much you can simplify it such as:
Collections.sort(list, new Comparator<List>() {
public int compare(List list1, List list2) {
return Integer.valueOf(list1.size()).compareTo(Integer.valueOf(list2.size()));
}
});
Upvotes: 2
Reputation: 7905
You can use any normal sort algorithm but instead of basing on value just base on the length of the element instead.
Upvotes: 0