Java8 Stream:2万字20个实例,玩转集合的筛选、归约、分组、聚合
JAVA 8新特性之 StreamApi Stream流的中间操作(二)
JAVA 8 StreamAPI 和 lambda表达式 总结(四)–stream的一些聚合操作
/**
* list -> map
*/
//将list数据变成以userid为key的map
Map<Integer,Person> map = list.stream().collect(Collectors.toMap((key->key.getId()),(value->value)));
//存在重复的key的写法
Map<Integer, Person> map = list.stream().collect(Collectors.toMap(Person::getId, a -> a, (k1, k2) -> k1));
//将list数据进行以userid进行分组,可以为userid
Map<Integer, List<Person>> map = list.stream().collect(Collectors.groupingBy(Person::getId));
//获取list集合中某个字段组成新的list
List<Integer> lists = list.stream().map(Person::getId).collect(Collectors.toList());
//集合根据某个字段去重
List<Person> lists = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getId))), ArrayList::new));
//过滤list中的某些数据
List<Person> lists = list.stream().filter(x -> !x.getId().equals(100)).collect(Collectors.toList());
//定义过滤规则
Predicate<PayPayMentListVo> success = x->x.getAlipaystate() == 2 || x.getWxpaystate() == 2;
for (Map.Entry en: timeMap.entrySet()) {
List<PayPayMentListVo> values = (List<PayPayMentListVo>) en.getValue();
//求满足规则的applymoney数据汇总
values.stream().filter(success).mapToLong(PayPayMentListVo::getApplymoney).sum();
}
//过滤
APActivityDict apActivityDict;
apActivityDict = listDictInfo.stream().filter(x -> ActivityDictEnum.appHomeTrailerConfig.getValue().equals(x.getId())).findFirst().orElse(null);
//resultList集合根据ApActivityRewardRecord 中的rewarddate字段倒叙排
resultList = resultList.stream().sorted(Comparator.comparing(ApActivityRewardRecord :: getRewarddate).reversed()).collect(Collectors.toList());
Collections.sort(gameList, Comparator.comparing(ApActivityYearGameVo::getCreatetime));
//先根据data倒叙,在根据createtime顺序
rankList=rankList.stream().sorted(Comparator.comparing(ActivityRank::getData,Comparator.reverseOrder()).thenComparing(ActivityRank::getCreatetime)).collect(Collectors.toList());
/**
*求和 0为初始值
*采用reduce进行数值操作会涉及到基本数值类型和引用数值类型之间的装箱、拆箱操作,因此效率较低。
*当流操作为纯数值操作时,使用数值流能获得较高的效率。
*/
//自定义求和
List<Person> list;
int age = list.stream().reduce(0, (person1,person2)->person1.getAge()+person2.getAge());
//用对象自带方法求和
List<Integer> list;
int age = list.stream().reduce(0, Integer::sum);
int age = list.stream().reduce(Integer::sum);
//数值计算
int sum = countStepCon.stream().mapToInt(ApActivityHallowmasCooperStep::getTasktype).sum();
//获取数字的个数、最小值、最大值、总和以及平均值
List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x).summaryStatistics();
System.out.println("Highest prime number in List : " + stats.getMax());
System.out.println("Lowest prime number in List : " + stats.getMin());
System.out.println("Sum of all prime numbers : " + stats.getSum());
System.out.println("Average of all prime numbers : " + stats.getAverage());