简体   繁体   中英

Finding minimum value of my ArrayList of float values

I'm having all sorts of problems trying to do something that I expected to be quite simple. I have an ArrayList of float values, and I want to return the minimum value in the list as a float. I expected something like this to work:

public float getMin(){
float min = Collections.min(Arrays.asList(listOfThings)));
return min;
} 

but I keep running into loads of incompatibility problems.

What's the most efficient way of doing this?

Thanks

If you use Collection as generic, Collection.min returns Object so you should convert it.

do this:

Object obj = Collections.min(arrayList);
Float f = Float.parseFloat(obj.toString());
return f.floatValue();

Or simply define ArrayList as

ArrayList<Float> 

and you don't need to convert it.

如果您使用的是Java8,则可以使用流对象来实现您的目标:

float value = list.stream().min(Comparator.<Float>naturalOrder()).get();

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