Java: finding previous and next value of a navigable set

Viewed 192

I have a navigable set right now that stores Integers, how could I find the previous and next elements from a specific element? I'm not sure how to use an iterator if that's how you could find those elements.

Example:

NavigableSet<Integer> values = new TreeSet<>(List.of(1, 2, 3, 4, 5));

Lets say, given 3, I want to get hands on the 2 (previous) or the 4 (next).

2 Answers

Higher & Lower

Check the official documentation: NavigableSet

There are the methods

  • higher : Returns the least element in this set strictly greater than the given element, or null if there is no such element.
  • lower : Returns the greatest element in this set strictly less than the given element, or null if there is no such element.

Example:

TreeSet<Integer> values = new TreeSet<>(List.of(1, 2, 4));

// 3 is not contained
int lower1 = values.lower(3); // 2
int higher1 = values.higher(3); // 4

// 2 is contained
int lower2 = values.lower(2); // 1
int higher2 = values.higher(2); // 4

Ceiling & Floor

In case you are not looking for strictly greater or smaller, there are also

  • ceiling: Returns the least element in this set greater than or equal to the given element, or null if there is no such element.
  • floor: Returns the greatest element in this set less than or equal to the given element, or null if there is no such element.

Example:

TreeSet<Integer> values = new TreeSet<>(List.of(1, 2, 4));

// 3 is not contained
int lower1 = values.floor(3); // 2
int higher1 = values.ceiling(3); // 4

// 2 is contained
int lower2 = values.floor(2); // 2
int higher2 = values.ceiling(2); // 2

Notes

Be careful with the methods returning null if there is no such element. Especially if you auto-unbox to int. I.e.

int result = values.lower(1);

will crash with a NullPointerException. Stick to Integer instead of int if you want to check for existence first.

There are also many more methods that do similar things, such as headSet or tailSet, which you can also combine with an iterator afterwards.

In a NavigableSet taken You can use floor method to get the "previous" element:

Returns the greatest element in this set less than or equal to the given element, or null if there is no such element.

and the ceiling to get the "next" element:

Returns the least element in this set greater than or equal to the given element, or null if there is no such element.

This solution can be used for any kind of object.

By the way You are using integers that have always greater or lower than another integer if they are not equals you can use higher or lower:

(higher) Returns the least element in this set strictly greater than the given element, or null if there is no such element.

(lower) Returns the greatest element in this set strictly less than the given element, or null if there is no such element.

Related