简体   繁体   English

查找浮点值的ArrayList的最小值

[英]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. 我有一个浮点值的ArrayList,我想以浮点数的形式返回列表中的最小值。 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. 如果使用Collection作为泛型,则Collection.min返回Object因此您应该对其进行转换。

do this: 做这个:

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

Or simply define ArrayList as 或者简单地将ArrayList定义为

ArrayList<Float> 

and you don't need to convert it. 而且您不需要转换它。

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

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

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

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