I would like to calculate the time between dates in an ArrayList
using java 8 lambda expressions. With the time between dates I mean: Date i - Date i-1, Date i-1 - Date i-2, etc. I am using java.util.Date
.
I already use this code in java 7, but I am just curious if streaming can shorten this up:
List<Date> dates = transactions.stream().map(Transaction::getTimestampEnd).sorted((d1, d2) -> d1.compareTo(d2)).collect(Collectors.toList());
List<Long> interArrivalTimes = new ArrayList<>();
AtomicInteger counter = new AtomicInteger();
dates.forEach(d -> {
int count = counter.getAndIncrement();
if (count != 0) {
Date previousDate = dates.get(count-1);
long time = d.getTime()-previousDate.getTime();
interArrivalTimes.add(time);
}
});
double mean = interArrivalTimes.stream().mapToLong(i -> i).average().getAsDouble();
After I have obtained the list of time differences, I want to calculate the mean. But it is more about the looping part that I would like to shorten. Maybe something with reduction or collection?
Any help is greatly appreciated!