Skip to content

Instantly share code, notes, and snippets.

@rokon12
Created June 29, 2025 02:17
Show Gist options
  • Save rokon12/b72591c6ce8ce510c84b9ee5676c88fd to your computer and use it in GitHub Desktop.
Save rokon12/b72591c6ce8ce510c84b9ee5676c88fd to your computer and use it in GitHub Desktop.
Code snippet from The Coding Café - for.java
public static <T, R extends Comparable<R>> Gatherer<T, ?, T>
takeWhileIncreasing(Function<T, R> valueExtractor) {
return Gatherer.of(
() -> new Object() { R lastValue = null; }, // 1️⃣ Anonymous class for state
(state, element, downstream) -> {
R value = valueExtractor.apply(element); // 2️⃣ Extract comparable value
if (state.lastValue == null || // 3️⃣ First element OR
value.compareTo(state.lastValue) > 0) { // value is increasing
state.lastValue = value; // 4️⃣ Update state
return downstream.push(element); // 5️⃣ Pass element along
}
return false; // 6️⃣ Stop gathering - sequence broken!
}
);
}
List<String> increasingLength = words.stream()
.gather(takeWhileIncreasing(String::length))
.toList();
System.out.println("Increasing length sequence: " + increasingLength);
// Output: [hello]
// Why? "hello"(5) → "world"(5) - not increasing, so we stop!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment