How to Get Lowest and Highest Value of TreeSet in Java


In this example we will show how to get the lowest and highest value of TreeSet object with first and last methods of java TreeSet class.

Source Code

package com.beginner.examples;

import java.util.TreeSet;

public class GetLowestHighestValueTreeSet {

	public static void main(String[] args) {
		
		//create TreeSet.
		TreeSet treeSet = new TreeSet();
		
		treeSet.add("A");
		treeSet.add("B");
		treeSet.add("C");
		treeSet.add("D");
		
		/*
		 * To get the lowest value currently stored in Java TreeSet using first method of TreeSet.
		 */
		System.out.println("Lowest value Stored in Java TreeSet is : " + treeSet.first());
		
		/*
		 * To get the highest value currently stored in Java TreeSet using last method of TreeSet.
		 */
		System.out.println("Highest value Stored in Java TreeSet is : " + treeSet.last());

	}

}

Output:

Lowest value Stored in Java TreeSet is : A
Highest value Stored in Java TreeSet is : D

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments