Java 8 Streams: How to call once the Collection.stream() method and retrieve an array of several aggregate values [duplicate]

一曲冷凌霜 提交于 2019-12-07 11:57:00

问题


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()

回答1:


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


来源:https://stackoverflow.com/questions/34620505/java-8-streams-how-to-call-once-the-collection-stream-method-and-retrieve-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!