I have a list of objects in Java with two timeStamp, like :
Obj (TimeStamp ts, TimeStamp generationTs, int value).
At the end, I don't want two items in the list with the same ts. If there are, I want to keep only the one with the most recent generationTs.
Actually, I have that code, it works, but I'd like to know if with streams, I can't do something better ?
list.sort(Collections.reverseOrder());
List<Obj> returnedList = Lists.newArrayList();
if (!list.isEmpty()) {
returnedList.add(list.get(0));
Iterator<Obj> i = list.iterator();
while (i.hasNext()) {
Obj lastObj = returnedList.get(returnedList.size() - 1);
Obj nextObj = i.next();
if (!lastObj.getTs().isEqual(nextObj.getTs())) {
returnedList.add(nextObj);
} else {
if (lastObj.getGenerationTs().isBefore(nextObj.getGenerationTs())) {
returnedList.remove(lastObj);
returnedList.add(nextObj);
}
}
}
}
If the list is :
{("2019-05-02T09:00:00Z", "2019-05-02T21:00:00Z", 1),
("2019-05-02T09:30:00Z", "2019-05-02T21:00:00Z", 2),
("2019-05-02T10:00:00Z", "2019-05-02T21:00:00Z", 3),
("2019-05-02T10:30:00Z", "2019-05-02T21:00:00Z", 4),
("2019-05-02T09:30:00Z", "2019-05-02T22:00:00Z", 5),
("2019-05-02T10:00:00Z", "2019-05-02T22:00:00Z", 6) }
It must returns :
{("2019-05-02T09:00:00Z", "2019-05-02T21:00:00Z", 1),
("2019-05-02T09:30:00Z", "2019-05-02T22:00:00Z", 5),
("2019-05-02T10:00:00Z", "2019-05-02T22:00:00Z", 6)
("2019-05-02T10:30:00Z", "2019-05-02T21:00:00Z", 4) }
List.removeIf, but you need to make sure that you don't remove element for its own existence.timestampas the key andObjas a value and then in themergeFunctionensure you fulfill yourgeneratedTscondition. Finally get the values of this map that you would be interested in.Bettercan be very subjective. If this is purely academic, fine. But if your code works, don't "fix" it.