Browse Source

WindowIterator should emit items in order when scrolling backwards.

Closes #2857
Original pull request: #2858
pull/2866/head
Christoph Strobl 3 years ago committed by Mark Paluch
parent
commit
d1568198d8
No known key found for this signature in database
GPG Key ID: 4406B84C1661DCD1
  1. 15
      src/main/java/org/springframework/data/support/WindowIterator.java
  2. 4
      src/test/java/org/springframework/data/domain/WindowIteratorUnitTests.java

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

@ -15,6 +15,7 @@ @@ -15,6 +15,7 @@
*/
package org.springframework.data.support;
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Function;
@ -81,7 +82,9 @@ public class WindowIterator<T> implements Iterator<T> { @@ -81,7 +82,9 @@ public class WindowIterator<T> implements Iterator<T> {
if (currentIterator == null) {
if (currentWindow != null) {
currentIterator = currentWindow.iterator();
currentIterator = isBackwardsScrolling(currentPosition)
? currentWindow.stream().sorted(Collections.reverseOrder()).iterator()
: currentWindow.iterator();
}
}
@ -116,15 +119,17 @@ public class WindowIterator<T> implements Iterator<T> { @@ -116,15 +119,17 @@ public class WindowIterator<T> implements Iterator<T> {
private static ScrollPosition getNextPosition(ScrollPosition currentPosition, Window<?> window) {
if (currentPosition instanceof KeysetScrollPosition ksp) {
if (ksp.scrollsBackward()) {
return window.positionAt(0);
}
if (isBackwardsScrolling(currentPosition)) {
return window.positionAt(0);
}
return window.positionAt(window.size() - 1);
}
private static boolean isBackwardsScrolling(ScrollPosition position) {
return position instanceof KeysetScrollPosition ksp ? ksp.scrollsBackward() : false;
}
/**
* Builder API to construct a {@link WindowIterator}.
*

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

@ -131,7 +131,7 @@ class WindowIteratorUnitTests { @@ -131,7 +131,7 @@ class WindowIteratorUnitTests {
assertThat(capturedResult).containsExactly("a", "b", "c", "d");
}
@Test // GH-2151
@Test // GH-2151, GH-2857
void considersBackwardKeysetScrolling() {
Window<String> initial = Window.from(List.of("c", "d"),
@ -152,6 +152,6 @@ class WindowIteratorUnitTests { @@ -152,6 +152,6 @@ class WindowIteratorUnitTests {
}).startingAt(ScrollPosition.keyset().backward());
List<String> items = Streamable.of(() -> iterator).toList();
assertThat(items).containsExactly("c", "d", "a", "b");
assertThat(items).containsExactly("d", "c", "b", "a");
}
}

Loading…
Cancel
Save