I thought of doing this by putting all of the sets in a list that would then be in a map, where the key is the size. I know the maximum size that a set could be(given to me), so I can just iterate between 0 and that number, get each list and then iterate through each list and put each set in an arraylist.
However, this seems horrifically clunky - is there a better way of doing this? Is there some way I can do a comparator function based on size?
Thanks
Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted as the parameter and returns a Collection sorted in the Ascending Order by default.
You can't, since a Set does not have random access methods (ie, . get() an element at a given index), which is basically required for sort algorithms ;) You can't since a HashSet doesn't have a defined order.
To sort an ArrayList in descending order we use reverseOrder() method as an argument of a sort() method. we can't directly call the reverseOrder() method. This method takes two parameters one is an object of ArrayList and the second parameter is the Collections.
To sort the ArrayList, you need to simply call the Collections. sort() method passing the ArrayList object populated with country names. This method will sort the elements (country names) of the ArrayList using natural ordering (alphabetically in ascending order).
You can provide a Comparator for that. and use Collections.sort()
class SizeComarator implements Comparator<Set<?>> {
@Override
public int compare(Set<?> o1, Set<?> o2) {
return Integer.valueOf(o1.size()).compareTo(o2.size());
}
}
ArrayList<Set<String>> arrayList = new ArrayList<Set<String>>();
Set<String> set1 = new HashSet<String>();
set1.add("A");
set1.add("B");
Set<String> set2 = new HashSet<String>();
set2.add("A");
arrayList.add(set1);
arrayList.add(set2);
Collections.sort(arrayList, new SizeComarator());
System.out.println(arrayList);
Output:
[[A], [A, B]]
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