简体   繁体   中英

Can I somehow exclude or filter out a value from Collections.Min/Collections.Max in java?

so I'm using Collections.min to find an object in an ArrayList, that contains the smallest integer value in one of it's elements. Basically comparing every element in the list.

Now, there are some objects in the list, that don't contain a value, so I had to set them to -1.

How would I exclude all the elements in the list that have an int value of -1, I don't see how I can apply an if statement.

temp = Collections.min(PollutionDatasetList, Comparator.comparingInt(Measurement::getLevel));

PollutionDatesetList - my list

Measurement - my class that's contained within the list

GetLevel - the integer value I'm comparing.

Just use the stream API:

 list.stream()
     .filter(m -> m.getLevel() >= 0)
     .min(Comparator.comparingInt(Measurement::getLevel))

A better return type for getLevel() would be OptionalInt . That would force every code dealing with levels to think about the case where the measurement has no level, and thus avoid bugs.

Since you are finding the minimum value using Collections.min so set the value of the objects that does not have a value to some large number instead of -1 say Integer.MAX_VALUE so it won't cause any more problem . I am not sure if this change will cause any problems to other modules of your program but it will definitely solve this issue of Collections.min .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM