Custom Sorting with TreeSet and TreeMap in Java


TreeSet and TreeMap support custom ordering of elements via comparators. Use them when ordered collections are needed.

Source Code

Set treeSet = new TreeSet(Comparator.reverseOrder());
treeSet.addAll(Arrays.asList("apple", "banana", "cherry"));
System.out.println(treeSet); // Outputs in reverse alphabetical order

Map treeMap = new TreeMap(Comparator.reverseOrder());
treeMap.put("c", "cherry");
treeMap.put("b", "banana");
treeMap.put("a", "apple");
System.out.println(treeMap); // Outputs keys in reverse alphabetical order
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments