/*** * 測試統計API <br> * 小結:<br> * 1.邏輯代碼應用{} 包起來 不寫{} 默認 + return <br> * 2.重載方法參數必須加類型聲明<br> * 3.書寫風格一個表達式只作一次抽象轉換 <br> * 4.最後斷鏈了 stream 內部會關閉流,再執行流之類操做會拋異常<br> * 5.表達式能夠象管道同樣綁定,接口與另外一實例方法綁定<br> * */ public static class Test4 { public static void main(String[] args) { List<Person> list1 = Person.ofList(); //sum 操做 long count = list1.stream().mapToInt(e -> e.getAge()).sum(); //reduce 操做 long count2 = list1.stream().mapToInt(e -> e.getAge()).reduce(0, (a,b)->a+b); //max 操做 OptionalInt max = list1.stream().mapToInt(e -> e.getAge()).max(); //avg 操做 OptionalDouble count1 = list1.stream().mapToInt(e -> e.getAge()).average(); //返回統計對象 IntSummaryStatistics statistics=list1.stream().mapToInt(e -> e.getAge()).summaryStatistics(); //groupBy 操做 Map<Integer, List<Person>> map=list1.stream().collect(Collectors.groupingBy(Person::getAge)); //collect 集合結束操做 Collectors.toList(); Collectors.toSet(); //每次it 回調peek list1.stream().filter(e->e.getAge()>2).mapToInt(e -> e.getAge()).peek( e->System.out.println("peek : "+e)).count(); //接口與實例方法綁定 list1.stream().forEach(System.out::println); //並行流 list1.parallelStream().count(); System.out.println("count : " + count); System.out.println("count2 : " + count2); System.out.println("aver : " + count1.getAsDouble()); System.out.println("max : " + max.getAsInt()); System.out.println("statistics count : " + statistics.getCount()); System.out.println("groupBy size : " + map.size()); Map<String,String> m = new HashMap<>(); m.getOrDefault("a", "5"); m.merge("a", "addValue", (a,b)-> a+b); System.out.println("map merge : " + m.get("a")); } }
import java.util.ArrayList; import java.util.List; public class Person { private String name; private int age; public static Person of(String name, int age) { Person result = new Person(); result.name = name; result.age = age; return result; } public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public static List<Person> ofList() { List<Person> result = new ArrayList<>(); for (int i = 0; i < 50; i++) { result.add(of("a" + i, i % 5)); } return result; } public String getName() { return name; } public int getAge() { return age; } }