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


this question has answer here:

i'm starting stream api in java 8.

here person object 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 code initializes list of objects person , gets number of objects, maximum age , minimum age, , create array of objects containing these 3 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 possible single call stream() method , return array of objects directly ?

object[] result = personslist.stream()...count()...max()...min() 

here's how solve 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 

Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -