If your set is in fact a NavigableSet<Foo>
(such as a TreeSet
), and Foo implements Comparable<Foo>
, you can use
Foo bar = set.floor(foo); // or .ceiling
if (foo.equals(bar)) {
// use bar…
}
(Thanks to @eliran-malka’s comment for the hint.)