/*** * 测试统计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; } }