Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Sets in ArrayList by Size

Tags:

java

sorting

set

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

like image 647
praks5432 Avatar asked Oct 23 '12 21:10

praks5432


People also ask

Is there a sort method for ArrayList?

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.

Can you sort sets in Java?

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.

How do I sort nested ArrayList?

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.

How do you sort an ArrayList of objects alphabetically in Java 8?

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).


1 Answers

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]]
like image 167
Amit Deshpande Avatar answered Sep 21 '22 20:09

Amit Deshpande