Created
June 29, 2025 02:04
-
-
Save rokon12/53f6ca3b9a421190642901dec6cc0bc4 to your computer and use it in GitHub Desktop.
Code snippet from The Coding Café - for.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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