Lower and Floor: Finding Elements Below a Given Value
You'll learn how to find elements in a sorted set that are just below a target value using two slightly different methods.
The Core Idea
NavigableSet (which TreeSet implements) provides two methods for finding elements below a given value:
lower(E e)— Returns the greatest element strictly less thane(doesn't includeeitself)floor(E e)— Returns the greatest element less than or equal toe(includeseif present)
Think of it like looking down a staircase. If you're standing on step 5:
lower(5)asks: "What's the highest step below where I'm standing?" → step 4floor(5)asks: "What's the highest step at or below where I'm standing?" → step 5 (you're on it!)
Visualizing the Difference
Suppose your TreeSet contains: {10, 20, 30, 40, 50}
TreeSet<Integer> set = new TreeSet<>();
set.add(10);
set.add(20);
set.add(30);
set.add(40);
set.add(50);
Integer result1 = set.lower(30); // 20 (strictly less than 30)
Integer result2 = set.floor(30); // 30 (30 is present, so return it)
Integer result3 = set.lower(35); // 30 (greatest below 35)
Integer result4 = set.floor(35); // 30 (35 not present, so same as lower)
Both methods return null if no qualifying element exists. For example, lower(10) would return null since nothing is below 10.
Key Takeaway: Use lower() when you need the element strictly below a value, and floor() when the value itself is acceptable if present—both are O(log n) operations in TreeSet.