2

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

2
  • 3
    Perhaps you could describe one problem you are running into from the loads you have. Commented Apr 12, 2014 at 14:21
  • Your code will work correctly if listOfThings is a float array. So I don't understand why you would would get any problems here. Commented Apr 12, 2014 at 14:43

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

No, it doesn't return Object: Collections.min() is typed. It returns the same type as the type of the collection.
3

If you're using Java8 you can use stream object to achieve your goal:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.