5

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?

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
mat_boy
  • 12,998
  • 22
  • 72
  • 116

2 Answers2

23
   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)) 
maczikasz
  • 1,113
  • 5
  • 12
4

You can also do

int min = list.stream().mapToInt(Obj::getField).min();
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289