Java8 array, list operation sink "5")-Java8 LAMBDA list statistics (sum, Maximum, minimum, average)

Source: Internet
Author: User

 Public classApple {PrivateInteger ID; PrivateString name; PrivateBigDecimal money; PrivateInteger num;  PublicApple (integer ID, String name, BigDecimal money, integer num) { This. ID =ID;  This. Name =name;  This. Money =Money ;  This. num =num; }}

 list<apple> applelist = new  arraylist<> (); //  Store Apple Object collection  apple apple1  = new  Apple (1, "Apple 1", new  BigDecimal ("3.25"), 10 = new  Apple (1, "Apple 2", new  BigDecimal ("1.35"), 20 = new  Apple (2, "banana", new  BigDecimal ("2.89"), 30 = new  Apple (3, "Lychee", new  BigDecimal ("9.99"), 40 

List.stream (). maptodouble (User::getheight). SUM ()//And List.stream (). maptodouble (User::getheight). Max ()// Maximum List.stream (). maptodouble (user::getheight). Min ()//min. list.stream (). maptodouble (User::getheight). Average ()// Average

1. List to MapID to Key,apple object as value, you can do this:/**  * List---MAP * Note that: * Tomap if the collection object has duplicate key, will error duplicate Key .... *  the ID of the APPLE1,APPLE12 is 1. *  */Map<integer, apple> applemap = Applelist.stream (). Collect (Collectors.tomap ( Apple::getid, A-A, (K1,K2)-K1); print applemap:{1=apple{id=1, name= ' Apple 1 ', money=3.25, num=10}, 2=apple{ id=2, name= ' banana ', money=2.89, num=30}, 3=apple{id=3, Name= ' lychee ', money=9.99, num=40}

2. Group the object elements in the List, grouped by an attribute, for example, by grouping IDs together with the same ID://list is grouped by ID map<integer,list<apple> >Map<integer, list<apple>> groupBy = applelist.stream (). Collect (Collectors.groupingby ( Apple::getid)); System.err.println ("groupBy:" +groupBy); {1=[apple{id=1, name= ' Apple 1 ', money=3.25, num=10}, apple{id=1, Name= ' Apple 2 ', money=1.35, num=20}], 2=[apple{id=2, name = ' banana ', money=2.89, num=30}], 3=[apple{id=3, name= ' lychee ', money=9.99, num=40}]}

3Filter: Filter out the set of eligible elements:// filter out eligible data list<apple> filterlist = Applelist.stream (). Filter (A-a.getname (). Equals ("banana")). Collect (Collectors.tolist ()); System.err.println ("filterlist:" +filterlist); [Apple{id=2, name= ' banana ', money=2.89, num=30}]

4. Sum: Sums the data in the collection according to a property: BigDecimal://Calculate Total AmountBigDecimal Totalmoney =Applelist.stream (). Map (Apple::getmoney). Reduce (Bigdecimal.zero, bigdecimal::add); System.err.println ("Totalmoney:" +totalmoney);//totalmoney:17.48Integer://Calculate Quantityintsum =Applelist.stream (). Maptoint (Apple::getnum). sum (); System.err.println ("Sum:" +sum);//sum:100List<Integer> cc =NewArraylist<>(); Cc.add (1); Cc.add (2); Cc.add (3);intsum = Cc.stream (). Maptoint (Integer::intvalue). sum ();//6

★5Collectors.groupingby to group, sort, and so on:ImportjavaX.Model.Student;Importjava.util.Arrays;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;Importjava.util.function.Function;Importjava.util.stream.Collectors; Public classFunctionx { Public Static voidMain (string[] args) {//1. Grouping CountList<student> list1= Arrays.aslist (NewStudent (1, "One", "Zhao"),NewStudent (2, "one", "Qian"),NewStudent (3, "I", "Sun")); //1.1 grouping counts based on an attributeMap<string,long> result1=List1.stream (). Collect (Collectors.groupingby (student::getgroupid,collectors.counting ()));        System.out.println (RESULT1); //1.2 counts against the entire entity object, when it is used as a stringMap<student,long> result2=List1.stream (). Collect (Collectors.groupingby (function.identity (), collectors.counting ()));        System.out.println (RESULT2); //1.3 Sorts the result according to the key value of the grouping, puts it in another map, and outputsMap<string,long> xmap=NewHashmap<>(); Result1.entryset (). Stream (). Sorted (map.entry.<string,long>comparingbykey (). Reversed ())//reversed does not take effect. foreachordered (x->Xmap.put (X.getkey (), X.getvalue ()));        System.out.println (XMAP); //2. Group and count one of the attributes worth sum or avg:id sumMap<string,integer> result3=List1.stream (). Collect (Collectors.groupingby (Student::getgroupid,collectors.summingint (Student::getid)        )        );    System.out.println (RESULT3); }}

Https://www.cnblogs.com/yangweiqiang/p/6934671.html

Java8 array, list operation sink "5")-Java8 LAMBDA list statistics (sum, Maximum, minimum, average)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.