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