Since you've already sorted the list in ascending order using Collections.sort(list), the element with the highest value is now at the end of the list.
In a LinkedList, you can remove the last element (i.e., the one with the highest value) using the removeLast() method:
java
list.removeLast();
That's it! This method removes and returns the last element from the list. If the list is empty, it throws a NoSuchElementException.
Here's a complete example:
java
import java.util.Collections;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
list.add(5);
list.add(2);
list.add(8);
list.add(3);
System.out.println("Before sorting: " + list);
Collections.sort(list); // sort in ascending order
System.out.println("After sorting: " + list);
// Remove the element with the highest value (now at the end of the list)
list.removeLast();
System.out.println("After removing highest value: " + list);
}
}
Output:
code
Before sorting: [5, 2, 8, 3]
After sorting: [2, 3, 5, 8]
After removing highest value: [2, 3, 5]
Why removeLast() and not remove() with an index?
While you could use list.remove(list.size() - 1) to achieve the same result, removeLast() is:
More readable and expressive, clearly conveying your intent.
More efficient, as it doesn't require calculating the index or bounds checking.
In a LinkedList, removeLast() simply updates the last node reference and adjusts the neighboring node pointers, making it an O(1) operation.
Now, go ahead and remove that highest value with confidence!
Bonus tip: If you wanted to remove the element with the lowest value (now at the beginning of the sorted list), use list.removeFirst(). Same idea, opposite end!