SortedSet last() method in Java

In Java, the SortedSet interface implements a collection to which the elements are sorted according to the natural ordering or a user-defined comparator. It is an integral part of the Java Collection Framework, which offers a wide variety of classes and interfaces for managing collections of objects.

Unlike other methods of SortedSet the last() method provides an access to highest (the last) element in the ordered set. The last() method can return the last element of the set considering the natural ordering of the elements or based on the comparator specified to get particular order at the moment the set was created. If there is no element present in the set, the last() method returns null.

Method Signature

E last()     

last: It is the name of the method. It indicates that the purpose of this method is to retrieve the last (highest) element in the sorted set.

E: It represents the return type of the method. In Java generics, E is a type parameter that stands for "Element". It indicates that the method returns an element of the same type as the elements stored in the SortedSet.

Various examples using SortedSet last method

1. Using TreeSet with Natural Ordering

The last() method of the SortedSet interface allows you to retrieve the last (highest) element in the sorted set efficiently. When used in conjunction with a TreeSet that maintains elements in natural ordering, this method provides a convenient way to access the largest element in the set.

Filename: Main.java

import java.util.*;

public class Main {

    public static void main(String[] args) {

        // Creating a TreeSet with natural ordering (ascending)

        SortedSet<Integer> sortedSet = new TreeSet<>();

        // Adding elements to the sorted set

        sortedSet.add(10);

        sortedSet.add(5);

        sortedSet.add(20);

        // Retrieving the last element

        Integer lastElement = sortedSet.last();

        // Printing the last element

        System.out.println("Last element: " + lastElement); // Output: 20

    }

}

Output:

Last element: 20

In this example, a TreeSet named sortedSet is created with natural ordering. It implements the SortedSet interface to maintain its elements in sorted order and then integer elements (10, 5, and 20) are added to the sortedSet. The last() method of the SortedSet interface is used to retrieve the last (highest) element from the sortedSet, this method efficiently accesses the highest element in the sorted set and the retrieved last element is printed as output.

2. Handling Empty SortedSet

When working with collections in Java, it's common to encounter situations where the collection might be empty. In such cases, attempting to retrieve the last element using the last() method without proper handling can lead to runtime exceptions, such as NoSuchElementException or NullPointerException. Therefore, it's crucial to implement appropriate checks to handle empty collections gracefully.

Filename: HES.java

import java.util.*;

public class HES {

    public static void main(String[] args) {

        // Creating an empty SortedSet

        SortedSet<Integer> sortedSet = new TreeSet<>();

        // Checking if the set is empty

        if (sortedSet.isEmpty()) {

            System.out.println("The sorted set is empty.");

        } else {

            // Retrieving the last element if the set is not empty

            Integer lastElement = sortedSet.last();

            System.out.println("Last element: " + lastElement);

        }

    }

}

Output:

The sorted set is empty.            

In this example, we create an empty SortedSet named sortedSet using the TreeSet implementation and use the isEmpty() method to check if the set is empty. If the set is empty, we print a message indicating that the set is empty. If the set is not empty, we safely retrieve the last element using the last() method and print it. However, since the set is empty in this example, the last() method is not invoked.

3. Using Custom Object in SortedSet

When using custom objects in a SortedSet, you need to ensure that the objects are comparable or provide a custom comparator to establish the sorting order, this allows the SortedSet implementation to maintain the elements in sorted order, facilitating efficient retrieval operations such as finding the last element using the last() method.

Algorithm

Step 1: Define a student class with attributes id and name and implement the Comparable interface to establish the natural ordering based on the student's ID.

Step 2: Implement the compareTo method to compare students based on their IDs. Create an empty TreeSet named sortedSet to store Student objects.

Step 3: Since Student implements Comparable, the TreeSet will automatically sort the elements based on the natural ordering defined in the compareTo method.

Step 4: Add Student objects to the sortedSet and the TreeSet will maintain the elements in sorted order based on the IDs of the students.

Step 5: Use the last() method of the SortedSet interface to retrieve the last (highest) Student object in the set and this method efficiently retrieves the last element from the sorted set.

Step 6: Print the details of the last Student object retrieved from the set and print the ID and name of the last student.

Filename: CustomObject.java

import java.util.*;

class Student implements Comparable<Student> {

    private int id;

    private String name;

    public Student(int id, String name) {

        this.id = id;

        this.name = name;

    }

    // Implementing compareTo method for natural ordering based on student ID

    @Override

    public int compareTo(Student other) {

        return Integer.compare(this.id, other.id);

    }

    // Getters for student attributes

    public int getId() {

        return id;

    }

    public String getName() {

        return name;

    }

}

public class CustomObject {

    public static void main(String[] args) {

        // Creating a TreeSet of Student objects

        SortedSet<Student> sortedSet = new TreeSet<>();

        // Adding Student objects to the sorted set

        sortedSet.add(new Student(101, "Alice"));

        sortedSet.add(new Student(103, "Bob"));

        sortedSet.add(new Student(102, "Charlie"));

        // Retrieving the last Student object

        Student lastStudent = sortedSet.last();

        // Printing details of the last Student

        System.out.println("Last student: ID - " + lastStudent.getId() + ", Name - " + lastStudent.getName());

    }

}

Output:

Last student: ID - 103, Name – Bob    

4. Using Custom Objects with Reverse Ordering

When working with custom objects in a SortedSet with reverse ordering, a custom comparator is defined to establish the sorting order based on specific attributes or criteria. By configuring the comparator to sort elements in reverse order (i.e., descending order), the SortedSet maintains elements accordingly, allowing efficient retrieval of the highest (last) element using the last() method.

Algorithm

Step 1: Define a Task class with attributes name and priority. Create a TreeSet with Custom Comparator i.e, an empty TreeSet named sortedSet.

Step 2: Use a custom comparator to establish reverse ordering based on the task's priority. The comparator is created using Comparator.comparingInt(Task::getPriority).reversed().

Step 3: Add Task objects to the sortedSet. The TreeSet maintains elements in reverse order based on the priority of tasks.

Step 4: Retrieve the Last (Highest Priority) Task: Use the last() method of the SortedSet interface to retrieve the last (highest priority) Task object in the set, this method efficiently retrieves the highest-priority task from the sorted set.

Step 5: Print the details of the highest priority Task object retrieved from the set. Print the name and priority of the task.

Filename: CustomObjectsReverse.java

import java.util.*;

class Task {

    private String name;

    private int priority;

    public Task(String name, int priority) {

        this.name = name;

        this.priority = priority;

    }

    public String getName() {

        return name;

    }

    public int getPriority() {

        return priority;

    }

}

public class CustomObjectsReverse {

    public static void main(String[] args) {

        // Creating a TreeSet with custom comparator (reverse sorting by priority)

        SortedSet<Task> sortedSet = new TreeSet<>(Comparator.comparingInt(Task::getPriority).reversed());

        // Adding Task objects to the sorted set

        sortedSet.add(new Task("Write report", 2));

        sortedSet.add(new Task("Review code", 3));

        sortedSet.add(new Task("Fix bugs", 1));

        // Retrieving and printing the highest priority task

        Task highestPriorityTask = sortedSet.last();

        System.out.println("Highest priority task: " + highestPriorityTask.getName() + ", Priority: " + highestPriorityTask.getPriority());

    }

}

Output:

Highest priority task: Fix bugs, Priority: 1 

5. Using SortedSet with LocalDate Objects

In Java, the LocalDate class from the java.time package represents a date without time-zone information. When working with collections of dates, the SortedSet interface along with its implementation classes like TreeSet ensures that dates are maintained in sorted order, facilitating operations such as retrieving the latest date using the last() method.

Filename: LocalDateObjects.java

import java.util.*;

import java.time.*;

public class LocalDateObjects {

    public static void main(String[] args) {

        // Creating a SortedSet of LocalDate objects

        SortedSet<LocalDate> sortedSet = new TreeSet<>();

        // Adding LocalDate objects to the sorted set

        sortedSet.add(LocalDate.of(2022, 5, 15));

        sortedSet.add(LocalDate.of(2023, 10, 20));

        sortedSet.add(LocalDate.of(2024, 3, 8));

        // Retrieving the latest date

        LocalDate latestDate = sortedSet.last();

        // Printing the latest date

        System.out.println("Latest date: " + latestDate);

    }

}

Output:

Latest date: 2024-03-08

In this example, we create a SortedSet named sortedSet to store LocalDate objects. The set automatically maintains dates in sorted order. We add some LocalDate objects representing different dates to the set. We retrieve the latest date from the set using the last() method, which efficiently returns the last (highest) element. Finally, we print the latest date obtained from the set.