Java8 Stream笔记
【参考文章】
Java设计模式
一、Strean example
(1) Filter
#过滤大于等于5的
List<Integer> list = new ArrayList<Integer>(){{
add(1);
add(3);
add(5);
add(7);
add(9);
}};
list.stream().filter(e->e>=5).forEach(System.out::println);
#转为数组
List<Integer> a = list.stream().filter(e->e>=5).collect(Collectors.toList());
System.out.println(a);
(2) Map 将一种类型转换为另一种类型
List<String> list = new ArrayList<String>(){{
add("1");
add("3");
add("5");
add("7");
add("9");
}};
list.stream().map(Integer::parseInt).forEach(System.out::println);
#输出数字 1 3 5 7 9
(3) Collection
Person p1 = new Person("zhangsan",26);
Person p2 = new Person("lisi",22);
Person p3 = new Person("wangwu",23);
List<Person> list = Arrays.asList(p1,p2,p3);
//装成list
List<Integer> ageList = list.stream().map(Person::getAge).collect(Collectors.toList());//[26,22,22]
//转成set
Set<Integer> ageSet = list.stream().map(Person::getAge).collect(Collectors.toSet());//[26,22]
//转成map,注:key不能相同,否则报错
Map<String, Integer> studentMap = list.stream().collect(Collectors.toMap(Person::getName, Person::getAge));
// {zhangsan=26, lisi=22, wangwu=22}
//字符串分隔符连接
String joinName = list.stream().map(Person::getName).collect(Collectors.joining(",", "(", ")"));
// (zhangsan,lisi,wangwu)
//聚合操作
//1.总数
Long count = list.stream().collect(Collectors.counting()); // 3
//2.最大年龄 (最小的minBy同理)
Integer maxAge = list.stream().map(Person::getAge).collect(Collectors.maxBy(Integer::compare)).get(); // 26
//3.所有人的年龄求和
Integer sumAge = list.stream().collect(Collectors.summingInt(Person::getAge)); // 70
//4.平均年龄
Double averageAge = list.stream().collect(Collectors.averagingDouble(Person::getAge)); // 23.333333333333332
// 带上以上所有方法
DoubleSummaryStatistics statistics = list.stream().collect(Collectors.summarizingDouble(Person::getAge));
System.out.println("count:" + statistics.getCount() + ",max:" + statistics.getMax() + ",sum:" + statistics.getSum() + ",average:" + statistics.getAverage());
//分组 按年龄分组
Map<Integer, List<Person>> ageMap = list.stream().collect(Collectors.groupingBy(Person::getAge));
//分区
//分成两部分,一部分大于10岁,一部分小于等于10岁
Map<Boolean, List<Person>> partMap = list.stream().collect(Collectors.partitioningBy(v -> v.getAge() > 10));
//规约
Integer allAge = list.stream().map(Person::getAge).collect(Collectors.reducing(Integer::sum)).get(); //40
版权声明:
本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自
晓!
喜欢就支持一下吧