Java 8 Streams.max() and Streams.min() example

I have been playing around with the new Stream interface in Java 8 and struggled briefly with the max() and min() methods.  Here is some example code I wrote for how to use the method max() from the Stream class.  The min() method will be very similar.

First, I had a Person class which is just a POJO with two fields and getters/setters:

public class Person {
    String name;
    int age;

    //Constructors and Getters/Setters are omitted for brevity
}

Finally, here is my example using streams:

 public static void main(String[] args) {
     Person obama = new Person("Barack Obama", 53);
     Person bush2 = new Person("George Bush", 68);
     Person clinton = new Person("Bill Clinton", 68);
     Person bush1 = new Person("George HW Bush", 90);
 
     Person[] personArray = new Person[] {obama, bush2, clinton, bush1};
     List<Person> personList = Arrays.asList(personArray);

    //Find Oldest Person
    final Comparator<Person> comp = (p1, p2) -> Integer.compare( p1.getAge(), p2.getAge());
    Person oldest = personList.stream()
                              .max(comp)
                              .get();

    //Find Youngest Person
    //  -This time instead create the Comparator as the argument to the min() method
    Person youngest = personList.stream()
                                .min((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge()))
                                .get();
}
Advertisements

About stevewall123

I am a Lead Software Engineer in Minneapolis working for Thomson Reuters. I am currently working on projects using Java, JavaScript, Spring, Drools, Hazelcast, Liquibase and Tomcat. Previously, I used C#, GWT, Grails, Groovy, JMS and JBoss Drools Guvnor. In the past I have worked on projects using J2EE, Swing, Webwork, Hibernate, Spring, Spring-WS, JMS, JUnit and Ant.
This entry was posted in Java, Java 8 and tagged , . Bookmark the permalink.

3 Responses to Java 8 Streams.max() and Streams.min() example

  1. Aleš Holý says:

    Check out the Comparator.comparing() method 😉

  2. Ganesh says:

    awesome example, simple to understand!!!

  3. Nagaraja says:

    Thanks really nice!!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s