Sorting Java Collections

Sorting Java Collections

1 Comment

Sorting collections is a common task that Java developers deal with on a daily bases.  The Java Collections class provides us with two sort() methods to sort all collections that implement the List interface.

Sorting Primitive Types & Strings

In the example below, we will create a list with ten random integers and sort the list using the sort() method, which takes in a List of objects.

import java.util.*;

public class Main {

    public static void main(String[] args) {

        List<Integer> numbers = new LinkedList<>();
        Random rand = new Random();

        // add 10 numbers to the list
        for (int index = 0; index < 10; index++) {
            // get a n number between 0 and 999
            int number = rand.nextInt(1000);
            // add number to list
            numbers.add(number);

        }
        // print out the numbers (unsorted)
        System.out.println("Before Sorting");
        numbers.forEach(number -> System.out.println(number));

        // print new line
        System.out.println();

        // sort the list
        Collections.sort(numbers);
        // print out the numbers (sorted)
        System.out.println("After Sorting");
        numbers.forEach(number -> System.out.println(number));

    }
}

When we run the code above this is the output:

Before Sorting
579
755
844
262
426
290
491
504
805
47

After Sorting
47
262
290
426
491
504
579
755
805
844

The numbers are now in sorted order. You can use this same method for sorting doubles, longs, and strings. To sort objects on a field like a name or age you have to use a comparator.

 

Sorting Object on a field Using a Comparator

For this example, we are going to sort a list of Students by their last name. To do this, we use the sort() which takes in a List of objects and a Comparator.

First, we need to create a class for students. You can have the code for the student class below.

public class Student {
    private String firstName;
    private String lastName;

    public Student(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }
}

In the code below we sort the students by their last name. We are comparing the last names on lines 23-26.

import java.util.*;

public class Main {

    public static void main(String[] args) {

        // create a list of students
        List<Student> students = new ArrayList<>();

        // add some students to the list
        students.add(new Student("Bob", "Peterson"));
        students.add(new Student("Kate", "Thompson"));
        students.add(new Student("Johnny", "Beware"));
        students.add(new Student("John", "Adams"));

        // print fist and last name of students before sorting
        System.out.println("Before Sorting");
        students.forEach(student -> System.out.println(student.getFullName()));

        // sort the list of students
        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                // compare last names for sorting
                return s1.getLastName().compareToIgnoreCase(s2.getLastName());
            }
        });

        // print new line
        System.out.println();
        // print first and last name if students after sorting
        System.out.println("After Sorting");
        students.forEach(student -> System.out.println(student.getFullName()));

    }
}

We can clean the code up a little by replacing the code on lines 21 – 27 above with this code:

students.sort(Comparator.comparing(Student::getLastName));

This code is doing the same thing behind the scenes but, is much easier to read.

When we run the code above this is the output:

Before Sorting
Bob Peterson
Kate Thompson
Johnny Beware
John Adams

After Sorting
John Adams
Johnny Beware
Bob Peterson
Kate Thompson

The students are now in sorted order by their last name.

Conclusion

In this post, you learned how to sort Java Collections that are primitive types and classes that you have created yourself.

 

Originally published at fluentjava.com

About Harrison Brock

Java and Go Software Engineer.

    You May Also Like