0

I have a list of objects. I need to find the minimum amount from a list of objects. But if there is a tie, then need to find the one with minimum Age. How to accomplish it using java 8?

class TestObject{
    private Double amount;
    private int age;
}

List<TestObject> objectList = getAllItems();
TestObject obj = objectList.stream()
            .min(Comparator
            .comparing(TestObject::getAmount))
            .get();
Hovercraft Full Of Eels
  • 280,125
  • 25
  • 247
  • 360
merry
  • 49
  • 4

1 Answers1

6

To combine two fields in the comparator you can use the answer linked by Goion or use the thenComparing function like this:

TestObject obj = objectList
      .stream() 
      .min(Comparator.comparing(TestObject::getAmount)
                     .thenComparing(TestObject::getAge))
      .get();
kasptom
  • 2,125
  • 2
  • 15
  • 19