How to Get HeadSet from TreeSet in Java


In this example, we may learn how to get the portion of TreeSet containing the values less than the specified value with HeadSet method of Java TreeSet class.

Source Code

package com.beginner.examples;

import java.util.SortedSet;
import java.util.TreeSet;

public class GetHeadSetFromTreeSet {

	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 a Head Set from Java TreeSet using  headSet method of TreeSet.
		 */
		SortedSet sortedSet = treeSet.headSet("D");
		
		System.out.println("Head Set Contains : " + sortedSet);

	}

}

Output:

Head Set Contains : [A, B, C]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments