I have a working piece of code written using traditional for loop as follows. I want to refactor it to use java 8 streams and remove the for loop. The output of the below code should be 3 as that is the longest consecutive list of numbers (4, 5 and 6)
List<Integer> weekDays = Lists.newArrayList(1, 2, 4, 5, 6);
List<Integer> consecutiveIntervals = Lists.newArrayList();
int maxConsecutiveTillNow = 1;
for (int i = 1; i < weekDays.size(); i++) {
if (weekDays.get(i) - weekDays.get(i - 1) == 1) {
maxConsecutiveTillNow++;
} else {
consecutiveIntervals.add(maxConsecutiveTillNow);
maxConsecutiveTillNow = 1;
}
}
consecutiveIntervals.add(maxConsecutiveTillNow);
System.out.println(consecutiveIntervals.stream()
.max(Integer::compareTo)
.get()
);