9

Suppose to have a class Obj

class Obj{

  int field;
}

and that you have a list of Obj instances, i.e. List<Obj> lst.

Now, how can I find in Java8 the minimum value of the int fields field from the objects in list lst?

2 Answers 2

25
   list.stream().min((o1,o2) -> Integer.compare(o1.field,o2.field))

Additional better solution from the comments by Brian Goetz

list.stream().min(Comparator.comparingInt(Obj::getField)) 
Sign up to request clarification or add additional context in comments.

2 Comments

This would be better as: list.stream().min(Comparator.comparingInt(Obj::getField))
Didn't know that one, thanks, I think your solution is the best so far
6

You can also do

int min = list.stream().mapToInt(Obj::getField).min();

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.