Skip to content

Commit

Permalink
Polishing.
Browse files Browse the repository at this point in the history
Use ReverseListIterator instead of Stream API to reduce overhead. ListIterator provides means to iterate backwards so we're wrapping the existing iterator.

See #2857.
Original pull request: #2858.
  • Loading branch information
mp911de committed Jun 16, 2023
1 parent 8671c00 commit 60877d7
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions src/main/java/org/springframework/data/support/WindowIterator.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
*/
package org.springframework.data.support;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.function.Function;

Expand Down Expand Up @@ -83,7 +84,7 @@ public boolean hasNext() {
if (currentIterator == null) {
if (currentWindow != null) {
currentIterator = isBackwardsScrolling(currentPosition)
? currentWindow.stream().sorted(Collections.reverseOrder()).iterator()
? new ReverseListIterator<>(currentWindow.getContent())
: currentWindow.iterator();
}
}
Expand Down Expand Up @@ -161,4 +162,28 @@ public WindowIterator<T> startingAt(ScrollPosition position) {
return new WindowIterator<>(windowFunction, position);
}
}

private static class ReverseListIterator<T> implements Iterator<T> {

private final ListIterator<T> delegate;

public ReverseListIterator(List<T> list) {
this.delegate = list.listIterator(list.size());
}

@Override
public boolean hasNext() {
return delegate.hasPrevious();
}

@Override
public T next() {
return delegate.previous();
}

@Override
public void remove() {
delegate.remove();
}
}
}

0 comments on commit 60877d7

Please sign in to comment.