How to print a java Set of Sets elements in sorted order?

Manoj Banik :

In my program I have a HashSet<HashSet<Integer>>, at then end of my program I'm printing the contents using the following statement,

System.out.println("Groups: " + allSets.toString());

It shows me this,

Groups: [[17], [19], [2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21], [11], [13]]

My answer is okay, but I would like to see it in sorted like,

Groups: [[2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21], [11], [13], [17], [19]]

I'm inserting into the Set all the single numbered sets in sorted order and I have to insert the big set at the end.

I tried with TreeSet but it doesn't work, (got some exceptions).

I solved my problem using List instead of Set,

I'm wondering, is there any way to get the same ordered output by using Set?

Louis Wasserman :

You can use a TreeSet for the outer set, you just need to give it a valid comparator. I would recommend something like

SortedSet<SortedSet<Integer>> outerSet = new TreeSet<SortedSet<Integer>>(
  Comparator.comparingInt(SortedSet::first));

(assuming Java 8).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=25299&siteId=1