I have a list of objects like this:
JavaScript
x
MyObject {
Date date;
int value;
}
I want to iterate the list and only keeps the objects where the dates differ. If there are two objects with the same date then I want to keep the object with the bigger value. Can this be achieved by using streams and predicates somehow?
Advertisement
Answer
You should use Map
and Map.merge()
instread of Stream
.
JavaScript
record MyObject(Date date, int value) {}
public static void main(String[] args) {
List<MyObject> list = List.of(
new MyObject(new Date(0), 0),
new MyObject(new Date(0), 1),
new MyObject(new Date(1000), 2));
Map<Date, MyObject> map = new LinkedashMap<>();
for (MyObject e : list)
map.merge(e.date(), e, (a, b) -> a.value() > b.value() ? a : b);
list = new ArrayList<>(map.values());
for (MyObject e : list)
System.out.println(e);
}
output:
JavaScript
MyObject[date=Thu Jan 01 09:00:00 JST 1970, value=1]
MyObject[date=Thu Jan 01 09:00:01 JST 1970, value=2]