Sorted Set Example – Ascending or Descending by comparator
In this Sorted Set example we show you how you can sort a java.util.Set
in ascending or descending order using a java.util.TreeSet
. The java.util.TreeSet
sorts the entries in natural order, which means that all the entries in the set are sorted in ascending order. To sort the entries of a set in descending order we can create a custom comparator.
Sorted Set Ascending order By TreeMap Example
To sort a set in Ascending order you can just add all the entries of the set into a java.util.TreeSet
which sorts all the entries in natural ascending order.
package com.memorynotfound.collections.set;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class SimpleSorting {
public static void main(String... args){
Set<Integer> random = new HashSet<Integer>();
for (int i = 0; i < 10; i++) {
random.add((int) (Math.random() * 100));
}
System.out.println("Initial Set: " + random);
Set<Integer> sorted = new TreeSet<Integer>(random);
System.out.println("Sorted Set: " + sorted);
}
}
Initial Set: [33, 22, 39, 7, 24, 9, 90, 14, 95]
Sorted Set: [7, 9, 14, 22, 24, 33, 39, 90, 95]
Sorted Set Descending order By TreeMap and Comparator Example
To sort a set in Descending order you can create a custom comparator which will sort all entries in Descending order after you added them.
package com.memorynotfound.collections.set;
import java.util.*;
public class ComparableSorting {
public static void main(String... args){
Set<Integer> random = new HashSet<Integer>();
for (int i = 0; i < 10; i++) {
random.add((int) (Math.random() * 100));
}
System.out.println("Initial Set: " + random);
Set<Integer> sorted = new TreeSet<Integer>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
});
sorted.addAll(random);
System.out.println("Sorted Set: " + sorted);
}
}
Initial Set: [36, 53, 21, 70, 87, 73, 74, 27, 93, 14]
Sorted Set: [93, 87, 74, 73, 70, 53, 36, 27, 21, 14]