5

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

praks5432
  • 7,246
  • 32
  • 91
  • 156

2 Answers2

8

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]]
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72
  • hmm so the thing that I'm sorting is really an object that is implemented as a private class - does this method still apply? – praks5432 Oct 23 '12 at 21:32
  • @praks5432 Added some more code so it will be easy for you to understand :) – Amit Deshpande Oct 23 '12 at 21:35
  • Beware of this implementation. I suspect that returning the same size to e.g. a `TreeSet<>#add()` will result to items being considered the same and dropped. – Ondra Žižka Mar 20 '16 at 18:25
3

In addition to the other (perfectly valid) answer, I'll just point out that you don't need to explicitly define a new class, you can just create one anonymously:

Collections.sort(myList, new Comparator<Set<?>>() {
    @Override
    public int compare(Set<?> o1, Set<?> o2) {
        return Integer.valueOf(o1.size()).compareTo(o2.size());
    }
});

Of couse, if you plan on using such a comparator multiple times, then I would consider defining it explicitly.


Relevant javadocs:

arshajii
  • 127,459
  • 24
  • 238
  • 287