Convert HashSet to a sorted TreeSet in Java

This little example shows how to convert a HashSet (or any Set) to a sorted TreeSet.
It’s probably more simple than you thought since the TreeSet, like other Collection objects, have a constructor that takes another Collection object. Since HashSet is a Collection object we can pass that into the constructor of the TreeSet and thus get a sorted Set.

Let’s say we fetch the time zones from the ZoneId class. It returns a HashSet of unsorted ZoneIds. We take that Set and create a TreeSet instead since we want to print out an ordered list of ZoneIds. This code example shows how:

First we print out the data from the unsorted HashSet just to see it’s not sorted. Then we print out the data from the TreeSet once it’s created. The output looks like this (the lists are cut off to save some space):

Search for more Java info on this site here:
Custom Search

Any thoughts or questions?