How to sort a Set in Java example

By , last updated July 4, 2019

There are different versions of Java available with different ways to sort collections of objects. We will be showing examples of how to sort a set of objects or strings alphabetically in Java 8, Java 7 and older versions using comparator.

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) {
	personsSorted.add(p);
}

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>() {
	@Override
	public int compare(Person o1, Person o2) {
		return o1.getName().compareTo(
				o2.getName());
	}
});

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 = items.stream().collect(Collectors.toList());

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.

Senior Software Engineer developing all kinds of stuff.