jdk1.8 -- Collectors 的使用
package com.collector; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors; import com.zpb.video_06.Dish;
import com.zpb.video_06.Dish.Type; /**
* @des Collector API的使用
* 三大功能:聚合 分组 统计
* @author zhao
* @date 2019年9月22日下午11:53:54
*
*/
public class CollectorsAPI { public static final List<Dish> menu = Arrays.asList(
new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("chicken", false, 400, Dish.Type.MEAT),
new Dish("french fries", true, 530, Dish.Type.OTHER),
new Dish("rice", true, 350, Dish.Type.OTHER),
new Dish("season fruit", true, 120, Dish.Type.OTHER),
new Dish("pizza", true, 550, Dish.Type.OTHER),
new Dish("prawns", false, 300, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH)); public static void main(String[] args) {
//1.求平均值
testAveragingDouble();
testaveragingInt();
testAveragingLong();
testCollectingAndThen(); //2.统计
testCounting();
testGroupByFunction();
testGroupByFunctionAndCollectors();
testGroupByFunctionAndAndCollectors();
testSummarizingInt();
} private static void testSummarizingInt() {
IntSummaryStatistics intSummary = menu.stream().collect(Collectors.summarizingInt(Dish::getCalories));
Optional.ofNullable(intSummary).ifPresent(System.out::println);
} private static void testGroupByFunctionAndAndCollectors() {
System.out.println("...testGroupByFunctionAndCollectors...");
Map<Type, Double> map = menu.stream().collect(Collectors.groupingBy(Dish::getType,Collectors.averagingDouble(Dish::getCalories)));
Optional.ofNullable(map.getClass()).ifPresent(System.out::println); //hashmap
//我们得到的是hashMap, 下面把它改成treeMap
TreeMap<Type, Double> map2 = menu.stream().collect(Collectors.groupingBy(Dish::getType, TreeMap::new, Collectors.averagingDouble(Dish::getCalories)));
Optional.ofNullable(map2.getClass()).ifPresent(System.out::println); } private static void testGroupByFunctionAndCollectors() {
System.out.println("...testGroupByFunctionAndCollectors...");
Optional.ofNullable(menu.stream().collect(Collectors.groupingBy(Dish::getType, Collectors.counting())))
.ifPresent(System.out::println); //每个分类下卡路里平均值
Optional.ofNullable(
menu.stream().collect(Collectors.groupingBy(Dish::getType, Collectors.averagingDouble(Dish::getCalories))))
.ifPresent(System.out::println);
}
private static void testGroupByFunction() {
System.out.println("...testGroupByFunction...");
Optional.ofNullable(menu.stream().collect(Collectors.groupingBy(Dish::getType)))
.ifPresent(System.out::println);
} private static void testCounting() {
System.out.println("...testCounting...");
Optional.ofNullable(menu.stream().collect(Collectors.counting())).ifPresent(System.out::println);
}
private static void testAveragingDouble() {
System.out.println("...testAveragingDouble...");
Optional.ofNullable(menu.stream().collect(Collectors.averagingDouble(Dish::getCalories)))
.ifPresent(System.out::println);
} private static void testaveragingInt() {
System.out.println("...testaveragingInt...");
Optional.ofNullable(menu.stream().collect(Collectors.averagingInt(Dish::getCalories)))
.ifPresent(System.out::println);
} private static void testAveragingLong() {
System.out.println("...testAveragingLong...");
Optional.ofNullable(menu.stream().collect(Collectors.averagingLong(Dish::getCalories)))
.ifPresent(System.out::println);
}
private static void testCollectingAndThen() {
/**
* collectingAndThen(Collector<T,A,R> downstream,Function<R,RR> finisher)
* 第1个参数是: Collector,也就是通过Collectors拿到的集合
* 第2个参数是:Function,也就是传入2个参数,R RR,返回的是RR
* 该方法最主要是要用好参数是怎么传入的
*/
System.out.println("...testCollectingAndThen..."); //1.获取到平均值,然后变成字符串输出
Optional.ofNullable(menu.stream().
collect(Collectors.collectingAndThen(Collectors.averagingLong(Dish::getCalories), a->"calories avg is "+a)))
.ifPresent(System.out::println); //2.得到指定集合,不能被别人修改
List<Dish> collect = menu.stream().filter(m->m.getType().equals(Type.MEAT))
.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
Optional.ofNullable(collect).orElseGet(ArrayList::new).forEach(System.out::println); } }
package com.collector; import java.awt.Menu;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.stream.Collectors; import com.collector.CollectorsAPI1;
import com.zpb.video_06.Dish;
import com.zpb.video_06.Dish.Type;
/**
* @des
* @author zhao
* @date 2019年9月24日上午12:13:00
*
*/
public class CollectorsAPI2 { static List<Dish> menu = CollectorsAPI1.menu; public final static void main(String[] args) { testGroupingByConcurrent();
testGroupingByConcurrentAndCollectors();
testGroupingByConcurrentAndSkipAndCollectors();
testJoining();
testJoiningAndPrefixAndSuffix();
testMapping();
testMaxBy();
testMinBy();
} //maxBy(Comparator<? super T> comparator) 按Comparator比较器规则,选出最大值
public static void testMaxBy() {
System.out.println(">>>>>>>>>>>>>>> testMaxBy >>>>>>>>>>>>>>>");
menu.stream().collect(Collectors.maxBy(Comparator.comparing(Dish::getCalories)))
.ifPresent(System.out::println);
} //maxBy(Comparator<? super T> comparator) 按Comparator比较器规则,选出最小值
public static void testMinBy() {
System.out.println(">>>>>>>>>>>>>>> testMaxBy >>>>>>>>>>>>>>>");
menu.stream().collect(Collectors.minBy(Comparator.comparing(Dish::getCalories)))
.ifPresent(System.out::println);
} public static void testMapping() {
System.out.println(">>>>>>>>>>>>>>> testMapping >>>>>>>>>>>>>>>");
/**
* mapping(Function<? super T, ? extends U> mapper, Collector<? super U, A, R> downstream) {
* 第1个参数得到的结果作为第2个参数操作的源数据
*/
Optional.ofNullable(menu.stream().collect(Collectors.mapping(Dish::getName, Collectors.joining(","))))
.ifPresent(System.out::println); } //连接操作
public static void testJoining() {
System.out.println(">>>>>>>>>>>>>>> testJoining() >>>>>>>>>>>>>>>");
Optional.ofNullable(menu.stream().map(Dish::getName).collect(Collectors.joining("#")))
.ifPresent(System.out::println);
}
public static void testJoiningAndPrefixAndSuffix() {
System.out.println(">>>>>>>>>>>>>>> testJoiningAndPrefixAndSuffix() >>>>>>>>>>>>>>>");
Optional.ofNullable(menu.stream().map(Dish::getName).collect(Collectors.joining(",","Name[","]")))
.ifPresent(System.out::println);
} public static void testGroupingByConcurrentAndSkipAndCollectors() {
System.out.println(">>>>>>>>>>>>>>> testGroupingByConcurrentAndSkipAndCollectors() >>>>>>>>>>>>>>>");
ConcurrentSkipListMap<Type, Double> skipListMap =
menu.stream().collect(Collectors.groupingBy(Dish::getType, ConcurrentSkipListMap::new,Collectors.averagingDouble(Dish::getCalories))); Optional.ofNullable(skipListMap.getClass()).ifPresent(System.out::println);
Optional.ofNullable(skipListMap).ifPresent(System.out::println); } public static void testGroupingByConcurrentAndCollectors() {
System.out.println(">>>>>>>>>>>>>>> testGroupingByConcurrentAndCollectors >>>>>>>>>>>>>>>");
Optional.ofNullable(menu.stream().collect(Collectors.groupingBy(Dish::getType, Collectors.averagingDouble(Dish::getCalories))))
.ifPresent(System.out::println);
}
//1.按类型分类,返回类型是:CurrentMap
public static void testGroupingByConcurrent() {
System.out.println(">>>>>>>>>>>>>>> testGroupingByConcurrent >>>>>>>>>>>>>>>");
Optional.ofNullable(menu.stream().collect(Collectors.groupingByConcurrent(Dish::getType)))
.ifPresent(System.out::println);
} }
package com.collector; /**
* @des
* @author zhao
* @date 2019年9月25日下午8:21:52
*
*/
import static com.collector.CollectorsAPI1.menu; import java.util.Comparator;
import java.util.DoubleSummaryStatistics;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.LongSummaryStatistics;
import java.util.Map;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors; import com.zpb.video_06.Dish; public class CollectorsAPI3 { public static void main(String[] args) { // partitioningBy(Predicate<? super T> predicate) 通过条件判断来分组
// 注意返回值是map类型的,当key为true时,表示是value中是符合判断条件的list集合,反之则不是
Map<Boolean, List<Dish>> collect = menu.stream().collect(Collectors.partitioningBy(Dish::isVegetarian));
Optional.ofNullable(collect).ifPresent(System.out::println); // partitioningBy(Predicate<? super T> predicate, Collector<? super T,A,D> downstream)
// 通过判断条件得到的集合,交给下一个collector进行处理
Map<Boolean, Double> collect2 = menu.stream()
.collect(Collectors.partitioningBy(Dish::isVegetarian, Collectors.averagingDouble(Dish::getCalories)));
Optional.ofNullable(collect2).ifPresent(System.out::println); // reducing(BinaryOperator<T> op) 聚合操作(用的是BinaryOperator本身的方法)
Optional<Dish> collect3 = menu.stream()
.collect(Collectors.reducing(BinaryOperator.maxBy(Comparator.comparing(Dish::getCalories))));
collect3.ifPresent(System.out::println); // reducing(T identity, BinaryOperator<T> op) T: 返回值类型值, op: 二元操作(怎么运算,用的是BinaryOperator父类BiFunction的方法)
Integer collect4 = menu.stream().map(Dish::getCalories).collect(Collectors.reducing(0, (d1, d2) -> d1 + d2));
Optional.ofNullable(collect4).ifPresent(System.out::println); //reducing(U identity, Function<? super T,? extends U> mapper, BinaryOperator<U> op)
//第1个参数:定义类型,
//第二个参数:定义了第2个参数必须是第1个参数的类型歌者是其子类
//第三个参数:op: 二元操作(怎么运算,用的是BinaryOperator父类BiFunction的方法)
menu.stream().collect(Collectors.reducing(0, Dish::getCalories,(d1,d2) -> d1 + d2)); //summarizingDouble(ToDoubleFunction<? super T> mapper) 求集合元素的平均结果
DoubleSummaryStatistics collect5 = menu.stream().collect(Collectors.summarizingDouble(Dish::getCalories)); //这里发生了隐式转换
Optional.ofNullable(collect5).ifPresent(System.out::println); //summarizingInt(ToIntFunction<? super T> mapper)
IntSummaryStatistics collect6 = menu.stream().collect(Collectors.summarizingInt(Dish::getCalories));
Optional.ofNullable(collect5).ifPresent(System.out::println); //Collectors.summarizingLong
LongSummaryStatistics collect7 = menu.stream().collect(Collectors.summarizingLong(Dish::getCalories));
Optional.ofNullable(collect7).ifPresent(System.out::println); //summingInt(ToIntFunction<? super T> mapper) 求某个元素的合
Integer collect8 = menu.stream().collect(Collectors.summingInt(Dish::getCalories));
Double collect9 = menu.stream().collect(Collectors.summingDouble(Dish::getCalories));
Long collect10 = menu.stream().collect(Collectors.summingLong(Dish::getCalories));
Optional.ofNullable(collect8).ifPresent(System.out::println);
Optional.ofNullable(collect9).ifPresent(System.out::println);
Optional.ofNullable(collect10).ifPresent(System.out::println); }
}
package com.collector; /**
* @des
* @author zhao
* @date 2019年9月25日下午9:36:49
*
*/
import static com.collector.CollectorsAPI1.menu; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors; import com.zpb.video_06.Dish;
import com.zpb.video_06.Dish.Type; public class CollectorsAPI4 { public static void main(String[] args) { // toCollection(Supplier<C> collectionFactory)
// 参数:只要是Collection的子类即可
ArrayList<Dish> collect = menu.stream().collect(Collectors.toCollection(ArrayList::new));
LinkedHashSet<Dish> collect2 = menu.stream().collect(Collectors.toCollection(LinkedHashSet::new)); // toConcurrentMap(Function<? super T,? extends K> keyMapper, Function<? super
// T,? extends U> valueMapper)
ConcurrentMap<String, Integer> collect3 = menu.stream()
.collect(Collectors.toConcurrentMap(Dish::getName, Dish::getCalories));
Optional.ofNullable(collect3).ifPresent(System.out::println);
System.out.println(">>>>>>>>>>>>>>>>>> 1");
// toConcurrentMap(Function<? super T,? extends K> keyMapper, Function<? super
// T,? extends U> valueMapper, BinaryOperator<U> mergeFunction)
// 第1个参数:通过Function拿到key
// 第2个参数:通过Function拿到value
// 第3个参数:将前面的value进行二次元操作
ConcurrentMap<String, Integer> collect4 = menu.stream().filter(d -> d.getCalories() > 500)
.collect(Collectors.toConcurrentMap(Dish::getName, Dish::getCalories, (d1, d2) -> d1 + d2));
Optional.ofNullable(collect4).ifPresent(System.out::println);
Optional.ofNullable(collect4.getClass()).ifPresent(System.out::println);
System.out.println(">>>>>>>>>>>>>>>>>> 2"); // 对同一类型的值进行++操作
menu.stream().collect(Collectors.toConcurrentMap(Dish::getType, v -> 1L, (a, b) -> a + b)); // toConcurrentMap(Function<? super T,? extends K> keyMapper, Function<? super
// T,? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M>
// mapSupplier)
// 由上面可知得到的类型是concurrentHashMap类型,第4个参数就是要转换成哪种map类型
// 第1个参数:通过Function拿到key
// 第2个参数:通过Function拿到value
// 第3个参数:将前面的value进行二次元操作
// 第4个参数:通过Supplier转换成其它类型
ConcurrentSkipListMap<Type, Long> collect5 = menu.stream().filter(d -> d.getCalories() > 500).collect(
Collectors.toConcurrentMap(Dish::getType, v -> 1L, (a, b) -> a + b, ConcurrentSkipListMap::new)); // toList()
List<Dish> collect6 = menu.stream().collect(Collectors.toList());
Optional.ofNullable(collect6).ifPresent(System.out::println); // toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends
// U> valueMapper)
Map<String, Long> collect7 = menu.stream().collect(Collectors.toMap(Dish::getName, V -> 1L)); // toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction)
Map<String, Long> collect8 = menu.stream().collect(Collectors.toMap(Dish::getName, v -> 1L, (a, b) -> a + b)); // toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper,
// BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier)
menu.stream().collect(Collectors.toMap(Dish::getType, v -> 1L, (a, b) -> a + b, ConcurrentSkipListMap::new));
System.out.println(">>>>>>>>>>>>>>>>>> 6"); menu.stream().collect(Collectors.collectingAndThen(Collectors.toMap(Dish::getName, Dish::getCalories), Collections::synchronizedMap)); Set<Dish> collect9 = menu.stream().collect(Collectors.toSet());
Optional.ofNullable(collect9).ifPresent(System.out::println);
}
}
jdk1.8 -- Collectors 的使用的更多相关文章
- JDK1.8新特性——Collector接口和Collectors工具类
JDK1.8新特性——Collector接口和Collectors工具类 摘要:本文主要学习了在Java1.8中新增的Collector接口和Collectors工具类,以及使用它们在处理集合时的改进 ...
- JDK1.8新特性(二):Collectors收集器类
一. 什么是Collectors? Java 8 API添加了一个新的抽象称为流Stream,我们借助Stream API可以很方便的操作流对象. Stream中有两个方法collect和collec ...
- 【JDK1.8】JDK1.8集合源码阅读——总章
一.前言 今天开始阅读jdk1.8的集合部分,平时在写项目的时候,用到的最多的部分可能就是Java的集合框架,通过阅读集合框架源码,了解其内部的数据结构实现,能够深入理解各个集合的性能特性,并且能够帮 ...
- Java进阶篇之十五 ----- JDK1.8的Lambda、Stream和日期的使用详解(很详细)
前言 本篇主要讲述是Java中JDK1.8的一些新语法特性使用,主要是Lambda.Stream和LocalDate日期的一些使用讲解. Lambda Lambda介绍 Lambda 表达式(lamb ...
- 【新特性】JDK1.8
一.简介 毫无疑问,Java 8是Java自Java 5(发布于2004年)之后的最重要的版本.这个版本包含语言.编译器.库.工具和JVM等方面的十多个新特性.在本文中我们将学习这些新特性,并用实际的 ...
- jdk1.8
Jdk1.8新特性 毫无疑问,Java 8是Java自Java 5(发布于2004年)之后的最重要的版本.这个版本包含语言.编译器.库.工具和JVM等方面的十多个新特性.在本文中我们将学习这些新特性, ...
- jdk1.8新特性应用之Collection
之前说了jdk1.8几个新特性,现在看下实战怎么玩,直接看代码: public List<MSG_ConMediaInfo> getConMediaInfoList(String live ...
- JDK1.8源码泛读之Arrays
jdk1.8包含的常用集合工具类,一般包括两个: 数组工具类:`java.util.Arrays ` 结合工具类:`java.util.Collections` 今天就结合源码对`java.util. ...
- java使用lambda表达式对List集合进行操作(JDK1.8)
1. 使用lambda表达式对List集合进行操作(JDK1.) List<TreeDto> collect = list.stream().filter(item -> item. ...
随机推荐
- this绑定问题
this是属性和方法“当前”(运行时)所在的对象.this是函数调用时发生的绑定,它的值只取决于调用位置(箭头函数除外). 函数调用的时候会产生一个执行上下文,this是对这个执行上下文的记录. ❌误 ...
- 51 Nod 1700 首尾排序法
1700 首尾排序法 有一个长度为n的数组 p1, p2, p3, ⋯, pnp1, p2, p3, ⋯, pn ,里面只包含1到n的整数,且每个数字都不一样.现在要对这个数组进行从小到大排序,排序的 ...
- 8月清北学堂培训 Day2
今天是赵和旭老师的讲授~ 背包 dp 模型 背包 dp 一般是给出一些“物品”,每个物品具有一些价值参数和花费参数,要求 在满足花费限制下最大化价值或者方案数. 最简单几种类型以及模型: 0/1背包: ...
- Python学习日记(六)——内置函数和文件操作(lambda)
lambda表达式 学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,即: # 普通条件语句 if 1 == 1: name = 'prime' else: name = 'c ...
- CF1214C
CF1214C 题意: 给你一个括号序列,问你时候能仅移动相邻的两个元素,使括号序列合法. 解法: 可以先考虑普通括号序列怎么做 这道题只交换相邻的两个元素,所以如果中间左括号和右括号的差值大于2时, ...
- 在SQLAlchemy ORM中动态变更表名
在开发过程中,经常会遇到几张表结构相同,仅仅表名不一样.这在直接使用SQL语句进行查询的环境中处理起来很简单,但如果使用了SQLAlchemy ORM之后,因在model定义时就确定了表名,就需要用其 ...
- 查看memcache版本
window: cmd中用telnet 127.0.0.1 11211这样的命令连接上memcache,然后直接输入stats就可以得到memcache服务器的版本. 注意:memcache的默认端口 ...
- HearthBuddy Ai调试实战1-->出牌的时候,少召唤了图腾就结束回合
期望通过ai的调试,来搞明白出牌的逻辑. 55是投火无面者63是恐狼前锋34是风怒36是自动漩涡打击装置13是空灵召唤者, "LocStringZhCn": "<b ...
- 开发软件-IntelliJ IDEA:百科
ylbtech-开发软件-IntelliJ IDEA:百科 IDEA 全称 IntelliJ IDEA,是java语言开发的集成环境,IntelliJ在业界被公认为最好的java开发工具之一,尤其在智 ...
- Linux下如何安装Nginx
看这就够了 https://segmentfault.com/a/1190000012435644 注意如果是远程浏览器访问是否启动了nginx,出现无法访问 服务器能够启动.访问不了页面 很大可能是 ...