I've to extract two values ( min & max ) from a List
of my custom objects, and currently I am creating streams twice and extracting it separately. I think it might be optimization to use a single stream and use the map or similar function to get both min and max in a single stream. Is that feasible?
public class MyClass {
public static class MyC {
double val;
public MyC(double val) {
this.val = val;
}
public double getVal() {return val;}
}
public static void main(String[] args) {
List<MyC> list = new ArrayList<>();
list.add(new MyC(10.0d));
list.add(new MyC(20.0d));
double min = Optional.ofNullable(list).stream()
.flatMap(List::stream)
.limit(13)
.map(MyC::getVal)
.min(Double::compare)
.orElse(getMinDefault());
double max = Optional.ofNullable(list).stream()
.flatMap(List::stream)
.limit(13)
.map(MyC::getVal)
.max(Double::compare)
.orElse(getMaxDefault());
}
private static double getMinDefault() {
return 1.0d;
}
private static double getMaxDefault() {
return 20.0d;
}
}