pppavan pppavan - 1 year ago 75
Java Question

Minimum date by streaming list with a list java 8

I am trying to write streams to iterate through list within a list to find the minimum date.The following is what i have tried.

listA.stream().flatMap(t -> t.listB().stream()).map(v ->v.getDate()).min((b1,b2 ) -> b1.compareTo(b2));

But the above piece of code is giving Optional but i need Date.Can someone tell where am i doing wrong

Answer Source

Optional allows you to avoid null values. It's protecting you, so to speak. You have to get the value from it. See the Javadocs

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

You may also choose to use Optional#orElse to avoid the check and provide a default date automatically when the Optional is empty.

In the case of Stream#min an empty Optional is returned if the stream is empty or one describing the minimum value. So, it's possible to call min, or max, on an empty stream.