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
  • 283,665
  • 25
  • 256
  • 373
merry
  • 49
  • 1
  • 5

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,363
  • 2
  • 16
  • 20