I'm looking for a way to emulate the following behavior with Java 8 streams. Given a stream of years,sort them so the top 10 values are outputed, such that after outputing a year, that is decreased and the iteration restarts resorting again:
If I input years 2005, 2020, 2000, 1967 and 2018 I expect the following results for a limit of 10:
2020
2019
2018 2018
2017 2017
2016 2016 2016
2015 ...
The test I am using is:
public class LazyTest {
public static void main(String[] args) {
Stream.of(2005,2020,2000,1967,2018)
.map(YearWrapper::new)
.sorted()
.limit(10)
.peek(year -> year.decreaseYear())
.forEach(System.out::println);
}
public static class YearWrapper implements Comparable<YearWrapper>{
private int currentYear;
public YearWrapper(int year){
this.currentYear=year;
}
public void decreaseYear(){
currentYear--;
}
@Override
public int compareTo(YearWrapper yearsToCompare) {
return Integer.compare(yearsToCompare.currentYear, this.currentYear);
}
@Override
public String toString(){
return String.valueOf(currentYear);
}
}
}
But it seems sorted() is not lazy at all. The whole sorting is done once at the beggining so the order is calculated before any further operation and therefore, the 5 values of the example are passed ordered one by one, so decrease() have no real effect on the iteration.
Is there any way to make sorted() lazy and being applied again to the remaining elements before streaming the next one?
Any other close approach would be much appreciated!!