Java headSet(element, booleanValue)

Java headSet(element, booleanValue)

The headSet method is a method of the SortedSet interface in Java, which is implemented by the TreeSet class. It returns a SortedSet containing the elements in the original set that are strictly less than the specified element.

Here is an example of how to use the headSet method:

SortedSet<String> set = new TreeSet<>();
set.add("apple");
set.add("banana");
set.add("orange");
set.add("pear");
set.add("strawberry");

SortedSet<String> headSet = set.headSet("orange", false);
// headSet contains ["apple", "banana"]
Source‮‬:www.lautturi.com

In this example, the set variable is a TreeSet object that stores a sorted set of strings. The headSet method is called with the element "orange" and the boolean value false. This returns a SortedSet containing the elements "apple" and "banana", which are strictly less than "orange".

The second argument to the headSet method, a boolean value, specifies whether the returned SortedSet should include the specified element. If the boolean value is true, the returned SortedSet will include the element. If the boolean value is false, the returned SortedSet will not include the element.

You can use the tailSet method of the SortedSet interface to get a SortedSet containing the elements in the original set that are strictly greater than the specified element.

For example:

SortedSet<String> tailSet = set.tailSet("orange", false);
// tailSet contains ["pear", "strawberry"]

You can use the subSet method of the SortedSet interface to get a SortedSet containing the elements in the original set that are within a specified range.

For example:

SortedSet<String> subSet = set.subSet("banana", "pear", false, false);
// subSet contains ["orange"]
Created Time:2017-11-03 22:21:03  Author:lautturi