Hienz :
I have a list of objects with the following structure:
public class ExampleObject {
private boolean someBoolean;
private int someInteger;
// getters, setters, constructor...
}
I need a method, that will return the integer -1 if any of the objects has the someBoolean field set to true, otherwise return the minimum of someInteger.
I could do it with simple for loop, is there a way to do it with one single stream? My problem was that both anyMatch and min() is terminating the stream.
Eran :
If someInteger
is non-negative, you can map each instance to either -1 or someInteger
based on the value of the boolean
property, and find the minimum:
OptionalInt min = list.mapToInt (o -> o.getSomeBoolean () ? -1 : o.getSomeInteger())
.min();
If someInteger
can be negative, you can map the instances for which the boolean
property it true
to Integer.MIN_VALUE
, and change the output to -1
if it's equal to Integer.MIN_VALUE
.