Java 8 Streams:如何调用Collection.stream()方法并检索多个聚合值的数组 [英] Java 8 Streams: How to call once the Collection.stream() method and retrieve an array of several aggregate values

查看:140
本文介绍了Java 8 Streams:如何调用Collection.stream()方法并检索多个聚合值的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Java 8中的Stream API开始。

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

这是我使用的Person对象:

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;
    }

  }

这是我的代码初始化a对象列表Person,它获取对象的数量,最大年龄和最小年龄,最后创建一个包含这三个值的对象数组:

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


推荐答案

以下是使用标准JDK 8 API解决此问题的方法:

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

结果:

Count: 3
Max  : 35
Min  : 25

这篇关于Java 8 Streams:如何调用Collection.stream()方法并检索多个聚合值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆