Sort a Java List Alphabetically First and then by Numbers

  • Last updated Apr 26, 2024

Learn how to sort a Java list alphabetically first and then by numbers.

Here's an example code to demonstrate the implementation of a Book class with a nested Comparators class for defining custom sorting behavior based on the book name:

import java.util.Comparator;

public class Book {
    private String id;
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Book [id=" + id + ", name=" + name + "]";
    }

    public static class Comparators {

        public static Comparator ORDER_BY_NAME_ASC = new Comparator() {

            @Override
            public int compare(Book book1, Book book2) {
                return existsNumber(book1.getName(), book2.getName())
                        ? isNumber(book1.getName()) ? 1 : -1
                        : book1.getName().compareToIgnoreCase(book2.getName());
            }
        };

        private static boolean isNumber(String s) {
            String pattern = "\\d.*";
            return s.matches(pattern);
        }

        private static boolean existsNumber(String o1, String o2) {
            return isNumber(o1) || isNumber(o2);
        }

    }
}

The Book class has two private fields: id and name. It also provides the necessary getter and setter methods.

The nested Comparators class defines a static comparator named ORDER_BY_NAME_ASC for sorting books by name in ascending order. This comparator is implemented using an anonymous inner class that overrides the compare method from the Comparator interface.

Within the compare method, the logic for sorting the books is defined. It checks if either book name contains a number using the isNumber method. If one of the book names contains a number, it prioritizes the book with a non-numeric name. Otherwise, it compares the names in a case-insensitive manner using the compareToIgnoreCase method.

The isNumber method uses a regular expression pattern (\\d.*) to check if a string starts with a digit.

The existsNumber method determines whether either of the given book names contains a number by calling the isNumber method.

Lets use the above example code to sort a list of Book objects based on their names in ascending order, with a special consideration for names containing numbers:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortingExample {

    public static void main(String[] args) {

        List books = new ArrayList<>();

        Book book1 = new Book();
        book1.setId("1");
        book1.setName("Candid");
        books.add(book1);

        Book book2 = new Book();
        book2.setId("2");
        book2.setName("Tutorials");
        books.add(book2);

        Book book3 = new Book();
        book3.setId("3");
        book3.setName("ASP dot net");
        books.add(book3);

        Book book4 = new Book();
        book4.setId("4");
        book4.setName("25 skills");
        books.add(book4);

        Book book5 = new Book();
        book5.setId("5");
        book5.setName("14 Days Learning");
        books.add(book5);

        Collections.sort(books, Book.Comparators.ORDER_BY_NAME_ASC);

        System.out.println("Sorted Books = " + books);

    }
}

Here, the SortingExample class contains the main method which serves as the entry point of the program. A list called books is created to hold instances of the Book class. Several Book objects are instantiated and added to the list, each with a unique ID and name. The Collections.sort method is used to sort the books list. The second argument is Book.Comparators.ORDER_BY_NAME_ASC, which specifies the custom comparator to be used for sorting. The custom comparator Book.Comparators.ORDER_BY_NAME_ASC is defined in the nested Comparators class inside the Book class. This comparator compares the books based on their names in ascending order. Finally, the sorted list of books is printed to the console.

The output of the above code is as follows:

Sorted Books = [
                Book [id=3, name=ASP dot net],
                Book [id=1, name=Candid], 
                Book [id=2, name=Tutorials], 
                Book [id=4, name=25 skills],
                Book [id=5, name=14 Days Learning]
                ]