我从 Java 8 中的 Stream API 开始。
这是我使用的 Person 对象:
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;
}
}
这是我的代码,它初始化一个 Person 对象列表,并获取对象的数量、最大年龄和最小年龄,最后创建一个包含这三个值的对象数组:
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));
是否可以对stream()
方法并直接返回对象数组?
Object[] result = personsList.stream()...count()...max()...min()