Skip to content

Commit d156819

Browse files
christophstroblmp911de
authored andcommitted
WindowIterator should emit items in order when scrolling backwards.
Closes #2857 Original pull request: #2858
1 parent 8aff631 commit d156819

File tree

2 files changed

+12
-7
lines changed

2 files changed

+12
-7
lines changed

src/main/java/org/springframework/data/support/WindowIterator.java

+10-5
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
*/
1616
package org.springframework.data.support;
1717

18+
import java.util.Collections;
1819
import java.util.Iterator;
1920
import java.util.NoSuchElementException;
2021
import java.util.function.Function;
@@ -81,7 +82,9 @@ public boolean hasNext() {
8182

8283
if (currentIterator == null) {
8384
if (currentWindow != null) {
84-
currentIterator = currentWindow.iterator();
85+
currentIterator = isBackwardsScrolling(currentPosition)
86+
? currentWindow.stream().sorted(Collections.reverseOrder()).iterator()
87+
: currentWindow.iterator();
8588
}
8689
}
8790

@@ -116,15 +119,17 @@ public T next() {
116119

117120
private static ScrollPosition getNextPosition(ScrollPosition currentPosition, Window<?> window) {
118121

119-
if (currentPosition instanceof KeysetScrollPosition ksp) {
120-
if (ksp.scrollsBackward()) {
121-
return window.positionAt(0);
122-
}
122+
if (isBackwardsScrolling(currentPosition)) {
123+
return window.positionAt(0);
123124
}
124125

125126
return window.positionAt(window.size() - 1);
126127
}
127128

129+
private static boolean isBackwardsScrolling(ScrollPosition position) {
130+
return position instanceof KeysetScrollPosition ksp ? ksp.scrollsBackward() : false;
131+
}
132+
128133
/**
129134
* Builder API to construct a {@link WindowIterator}.
130135
*

src/test/java/org/springframework/data/domain/WindowIteratorUnitTests.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ void allowsToIterateAllWindows() {
131131
assertThat(capturedResult).containsExactly("a", "b", "c", "d");
132132
}
133133

134-
@Test // GH-2151
134+
@Test // GH-2151, GH-2857
135135
void considersBackwardKeysetScrolling() {
136136

137137
Window<String> initial = Window.from(List.of("c", "d"),
@@ -152,6 +152,6 @@ void considersBackwardKeysetScrolling() {
152152
}).startingAt(ScrollPosition.keyset().backward());
153153

154154
List<String> items = Streamable.of(() -> iterator).toList();
155-
assertThat(items).containsExactly("c", "d", "a", "b");
155+
assertThat(items).containsExactly("d", "c", "b", "a");
156156
}
157157
}

0 commit comments

Comments
 (0)