People,
Consider the following example, given the list of Trade objects that I need to return a code containing the volume of trade for 24 hours, 7 days, 30 days and all the time.
Using a simple old iterator, this requires only one iteration over the collection.
I am trying to do the same using Java 8 and Lambda threads. I came up with this code that looks elegant, works great, but requires 4 iterations over the list:
public static final int DAY = 24 * 60 * 60; public double[] getTradeVolumes(List<Trade> trades, int timeStamp) { double volume = trades.stream().mapToDouble(Trade::getVolume).sum(); double volume30d = trades.stream().filter(trade -> trade.getTimestamp() + 30 * DAY > timeStamp).mapToDouble(Trade::getVolume).sum(); double volume7d = trades.stream().filter(trade -> trade.getTimestamp() + 7 * DAY > timeStamp).mapToDouble(Trade::getVolume).sum(); double volume24h = trades.stream().filter(trade -> trade.getTimestamp() + DAY > timeStamp).mapToDouble(Trade::getVolume).sum(); return new double[]{volume24h, volume7d, volume30d, volume}; }
How can I achieve the same using only one iteration through the list?
java lambda java-8 java-stream
lyaffe
source share