Below is my code to find the contact object with the latest begin dateTime. DateTime is shown as an object.
Is there any method to simplify this code using streams and comparators.
public ContactData getLatestContact(ContactData[] contacts) { int latestContact = 0; for (int i = 1; i < contacts.length; i++) { if (DateTimeToolkit.compare(contacts[i].begin, contacts[latestContact].begin) > 0) { latestContact = i; } } return contacts[latestContact]; }
Advertisement
Answer
I’m assuming that begin is a java.util.Date or any other Comparable? Then you could do:
public ContactData getLatestContact(ContactData[] contacts) { return Stream.of(contacts).sorted((a, b) -> DateTimeToolkit.compare(a.begin, b.begin)).findFirst().get(); }