I would like to calculate the time between dates in ArrayList
using java 8 lambda expressions. Over time between dates, I mean: Date i - Date i-1, Date i-1 - Date i-2, etc. I use java.util.Date
.
I already use this code in java 7, but I'm just wondering if streaming can shorten this:
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 got a list of time differences, I want to calculate the average. But this is more about the cycle, which I would like to shorten. Maybe something with a reduction or assembly?
Any help is much appreciated!
source
share