简体   繁体   English

我可以以某种方式从java中的Collections.Min / Collections.Max中排除或过滤出一个值吗?

[英]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. 所以我正在使用Collections.min在ArrayList中找到一个对象,该对象在其元素之一中包含最小的整数值。 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. 现在,列表中有一些对象不包含值,因此我不得不将它们设置为-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. 如何排除列表中所有具有-1的int值的元素,我看不到如何应用if语句。

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

PollutionDatesetList - my list PollutionDatesetList-我的列表

Measurement - my class that's contained within the list 测量-列表中包含的我的班级

GetLevel - the integer value I'm comparing. GetLevel-我正在比较的整数值。

Just use the stream API: 只需使用流API:

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

A better return type for getLevel() would be OptionalInt . getLevel()更好的返回类型是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 . 由于您是使用Collections.min查找最小值的,因此将没有值的对象的值设置为较大的值而不是-1,则说Integer.MAX_VALUE,这样就不会引起任何问题。 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 . 我不确定此更改是否会对程序的其他模块造成任何问题,但肯定会解决Collections.min的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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