How to sort a Set in Java example

By , last updated September 2, 2016

There are different versions of Java available with different ways to sort collections of objects. We will be showing examples of sorting a set of objects alphabetically with both Java 8 and older versions.

For this example we will take a Person object and put them all in a set. Each Person have a name and we will sort our collection of Person object alphabetically. It means that we need to implement a comparator which compares Strings.

public class Person {
    private String name;

    public String getName() {
        return name;

Let’s assume we can’t implement a compareTo methods inside a Person class. How do we go ahead and compare the objects?

In Java 7 and earlier we would go with overriding the compare method inside a Comparator class. We would than use a compareTo method to compare the strings.

First things first. We can’t sort a Java Set collection by calling Collections.sort() method on a Set. That is because most implementations of Java Set doesn’t have a concept of order. A Set is something without an order by definition in Java.

In order to sort a Java Set we need to convert it to a list first.

Java 7 and earlier

Set<Person> items = getPersons();

List<Person> personsSorted = new ArrayList<>();
for(Person p : items) {

Now that we have an ArrayList, we can use Collections.sort() method and provide our custom anonymous inner Comparator class that compares Person’s names and sorts the list alphabetically.

Collections.sort(personsSorted, new Comparator<Person>() {
	public int compare(Person o1, Person o2) {
		return o1.getName().compareTo(

Java 8

In Java 8 there are a lot of new cool features. One of them is streams. It is much easier and more beautiful to convert a Set into a List by using a stream method:

Set<Person> items = getPersons();

List<Person> personsSorted =;

Another new feature in Java 8 is lambdas. Lambdas are expressions which recognize the object type from the context.

Collections.sort(personsSorted, (o1, o2) -> o1.getName().compareTo(o2.getName()));

The code written in Java 8 is more elegant and is probably faster too.


Be the first to comment.

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>