3

I'm starting with the Stream API in Java 8.

Here is my Person object I use:

public class Person {

    private String firstName;
    private String lastName;
    private int age;

    public Person(String firstName, String lastName, int age) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
    }

    public String getFirstName() {
      return firstName;
    }

    public String getLastName() {
      return lastName;
    }

    public int getAge() {
      return age;
    }

  }

Here is my code which initializes a list of objects Person and which gets the number of objects, the maximum age and the minimum age, and finally create an array of objects containing these three values:

List<Person> personsList = new ArrayList<Person>();

personsList.add(new Person("John", "Doe", 25));
personsList.add(new Person("Jane", "Doe", 30));
personsList.add(new Person("John", "Smith", 35));

long count = personsList.stream().count();
int maxAge = personsList.stream().mapToInt(Person::getAge).max().getAsInt();
int minAge = personsList.stream().mapToInt(Person::getAge).min().getAsInt();

Object[] result = new Object[] { count, maxAge, minAge };
System.out.println(Arrays.toString(result));

Is it possible to do a single call to the stream() method and to return the array of objects directly ?

Object[] result = personsList.stream()...count()...max()...min()
Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
  • 2
    Using `IntSummaryStatistics`: `personsList.stream().mapToInt(Person::getAge).summaryStatistics()` – Tunaki Jan 05 '16 at 20:21
  • 1
    @Tunaki: While this question has certainly been asked before, I think that the one you linked as a duplicate is a particularly poor example, compared to this very specific question... – Lukas Eder Jan 05 '16 at 20:26

1 Answers1

4

Here's how to solve this with standard JDK 8 API:

IntSummaryStatistics summary = personsList.stream().collect(
    Collectors.summarizingInt(Person::getAge));
System.out.println("Count: " + summary.getCount());
System.out.println("Max  : " + summary.getMax());
System.out.println("Min  : " + summary.getMin());

Result:

Count: 3
Max  : 35
Min  : 25
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509