Home > other >  Finding the latest dates in a set of objects
Finding the latest dates in a set of objects

Time:04-30

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

CodePudding user response:

Your solution works just fine and if don't have to change it just keep it.

But for educational purposes let's break it down and try to express the same behavior with a stream since you asked for it. You want to find the latest date... Or in other terms the maximum value of the set. Luckily a java stream exposes such a method Stream#max(Comparator)

SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss" );
Person p1 = new Person( "Bill", dateFormat.parse( "2011-01-01 00:00:00" ) );
Person p2 = new Person( "Ray", dateFormat.parse( "2014-01-12 00:00:00" ) );
Person p3 = new Person( "Mike", dateFormat.parse( "2011-01-01 00:00:00" ) );
Person p4 = new Person( "Kate", dateFormat.parse( "2001-01-01 00:00:00" ) );

Person max = Stream.of( p1, p2, p3, p4 ).max( Comparator.comparing( Person::getDate ) ).orElseThrow();

System.out.println( max ); // Prints Person{name='Ray', date=Sun Jan 12 00:00:00 CET 2014} at least with the toString() method of my dummy class.

CodePudding user response:

You can use a stream with a reduce as follows:

Person person = s.stream()
        .reduce((youngest, current) -> youngest.birth.compareTo(current.birth) < 0 ? current : youngest)
        .orElseThrow();

System.out.println(person.name   " "   person.birth);
  • Related