I am looking to find the person with the most recent date from a set by comparing the birth Date which is a Date data type. Here is an experiment that I did.
public class Person {
public String name;
public Date birth;
public Person(String name, Date birth) {
this.name = name;
this.birth = birth;
}
}
and a Main class:
public static void main(String[] args) throws ParseException {
Person p1 = new Person("Bill", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2011-01-01 00:00:00"));
Person p2 = new Person("Ray", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2014-01-12 00:00:00"));
Person p3 = new Person("Mike", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2011-01-01 00:00:00"));
Person p4 = new Person("Kate", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2001-01-01 00:00:00"));
Set<Person> s = new HashSet<>();
s.add(p1);
s.add(p2);
s.add(p3);
s.add(p4);
Person temp = p1;
for (Person i : s) {
if (temp.birth.compareTo(i.birth) < 0) {
temp = i;
}
}
System.out.println(temp.name + " " + temp.birth);
}
}
It is working ok as it is now, but it does not if I will not equal temp = p1 (example Person temp = null). Is there a better way to do that without using an extra variable? Maybe with a stream? Thank you