Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8: select min value from specific field of the objects in a list

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?

like image 791
mat_boy Avatar asked Apr 16 '14 12:04

mat_boy


People also ask

How do you find the max and min of a list in Java 8?

toList()); T min = sorted. get(0); T max = sorted. get(sorted. size() - 1);

How do you check if a value is present in list of objects in Java?

ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.


2 Answers

   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)) 
like image 65
maczikasz Avatar answered Sep 30 '22 12:09

maczikasz


You can also do

int min = list.stream().mapToInt(Obj::getField).min();
like image 33
Aniket Thakur Avatar answered Sep 30 '22 13:09

Aniket Thakur