Java Collection, TreeSet Exercises: Get the first and last elements in a tree set

Java Collection, TreeSet Exercises: Exercise-5 with Solution

Write a Java program to get the first and last elements in a tree set.

Sample Solution:

Java Code:

import java.util.TreeSet;
  public class Exercise5 {
  public static void main(String[] args) {
  TreeSet<String> tree_set = new TreeSet<String>();
  System.out.println("Tree set: ");

   // Find first element of the tree set
    Object first_element = tree_set.first();
    System.out.println("First Element is: "+first_element);
    // Find last element of the tree set
    Object last_element = tree_set.last();
    System.out.println("Last Element is: "+last_element);

Sample Output:

Tree set:                                                              
[Black, Green, Orange, Red, White]                                     
First Element is: Black                                                
Last Element is: White 


Flowchart: Get the first and last elements in a tree set

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Create a reverse order view of the elements contained in a given tree set.
Next: Clone a tree set list to another tree set.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Share this Tutorial / Exercise on : Facebook and Twitter

Java: Tips of the Day


Converts to enum to Map where key is the name and value is Enum itself.

public static <E extends Enum<E>> Map<String, E> getEnumMap(final Class<E> enumClass) {
    return Arrays.stream(enumClass.getEnumConstants())
            .collect(Collectors.toMap(Enum::name, Function.identity()));

Ref: https://bit.ly/3xXcFZt