JAVA8 ARRAY、LIST操作 汇【5】)- JAVA8 LAMBDA LIST统计(求和、最大、最小、平均)

public class Apple {
    private Integer id;
    private String name;
    private BigDecimal money;
    private Integer num;
    public Apple(Integer id, String name, BigDecimal money, Integer num) {
        this.id = id;
        this.name = name;
        this.money = money;
        this.num = num;
    }
}


List<Apple> appleList = new ArrayList<>();//存放apple对象集合
Apple apple1 =  new Apple(1,"苹果1",new BigDecimal("3.25"),10);
Apple apple12 = new Apple(1,"苹果2",new BigDecimal("1.35"),20);
Apple apple2 =  new Apple(2,"香蕉",new BigDecimal("2.89"),30);
Apple apple3 =  new Apple(3,"荔枝",new BigDecimal("9.99"),40);
appleList.add(apple1);
appleList.add(apple12);
appleList.add(apple2);
appleList.add(apple3);

list.stream().mapToDouble(User::getHeight).sum()//和
list.stream().mapToDouble(User::getHeight).max()//最大
list.stream().mapToDouble(User::getHeight).min()//最小
list.stream().mapToDouble(User::getHeight).average()//平均值

1. List转Map
id为key,apple对象为value,可以这么做:
/**
* List -> Map
* 需要注意的是:
* toMap 如果集合对象有重复的key,会报错Duplicate key ....
* apple1,apple12的id都为1。
* 可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
*/
Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));
打印appleMap:
{1=Apple{id=1, name='苹果1', money=3.25, num=10}, 2=Apple{id=2, name='香蕉', money=2.89, num=30}, 3=Apple{id=3, name='荔枝', money=9.99, num=40}}


2. 分组
List里面的对象元素,以某个属性来分组,例如,以id分组,将id相同的放在一起:
//List 以ID分组 Map<Integer,List<Apple>>
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId)); System.err.println("groupBy:"+groupBy);
{1=[Apple{id=1, name='苹果1', money=3.25, num=10}, Apple{id=1, name='苹果2', money=1.35, num=20}], 2=[Apple{id=2, name='香蕉', money=2.89, num=30}], 3=[Apple{id=3, name='荔枝', money=9.99, num=40}]}

3. 过滤filter: 从集合中过滤出来符合条件的元素(map只是覆盖属性,filter根据判断属性来collect宿主bean):
//过滤出符合条件的数据
List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList()); System.err.println("filterList:"+filterList);
[Apple{id=2, name='香蕉', money=2.89, num=30}]

4. 求和: 将集合中的数据按照某个属性求和:
BigDecimal:
//计算 总金额
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
System.err.println("totalMoney:"+totalMoney); //totalMoney:17.48 Integer:
//计算 数量
int sum = appleList.stream().mapToInt(Apple::getNum).sum();
System.err.println("sum:"+sum); //sum:100 List<Integer> cc = new ArrayList<>();
cc.add(1);cc.add(2);cc.add(3);
int sum = cc.stream().mapToInt(Integer::intValue).sum();//6


★5 Collectors.groupingBy进行分组、排序等操作:
import javaX.Model.Student; import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors; public class FunctionX {
public static void main(String[] args) {
//1.分组计数
List<Student> list1= Arrays.asList(new Student(1,"one","zhao"),new Student(2,"one","qian"),new Student(3,"two","sun"));
//1.1根据某个属性分组计数
Map<String,Long> result1=list1.stream().collect(Collectors.groupingBy(Student::getGroupId,Collectors.counting()));
System.out.println(result1);
//1.2根据整个实体对象分组计数,当其为String时常使用
Map<Student,Long> result2=list1.stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println(result2);
//1.3根据分组的key值对结果进行排序、放进另一个map中并输出
Map<String,Long> xMap=new HashMap<>();
result1.entrySet().stream().sorted(Map.Entry.<String,Long>comparingByKey().reversed()) //reversed不生效
.forEachOrdered(x->xMap.put(x.getKey(),x.getValue()));
System.out.println(xMap); //2.分组,并统计其中一个属性值得sum或者avg:id总和
Map<String,Integer> result3=list1.stream().collect(
Collectors.groupingBy(Student::getGroupId,Collectors.summingInt(Student::getId))
);
System.out.println(result3); }
}
JAVA8 ARRAY、LIST操作 汇【5】)- JAVA8 LAMBDA LIST统计(求和、最大、最小、平均)的更多相关文章
- 【java多线程】java8的流操作api和fork/join框架
		
原文:https://blog.csdn.net/u011001723/article/details/52794455/ 一.测试一个案例,说明java8的流操作是并行操作 1.代码 package ...
 - Java8新特性(一)之Lambda表达式
		
.personSunflowerP { background: rgba(51, 153, 0, 0.66); border-bottom: 1px solid rgba(0, 102, 0, 1); ...
 - Java8 特性详解(一) Lambda
		
为什么要使用lambda表达式 从函数式接口说起 理解Functional Interface(函数式接口)是学习Java8 lambda表达式的关键所在. 函数式接口的定义其实很简单:任何接口,如果 ...
 - 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈  绝对值?相对值
		
小结: 1. 常数时间内检索到最小元素 2.存储 存储绝对值?相对值 存储差异 3. java-ide-debug 最小栈 - 力扣(LeetCode)https://leetcode-cn.com/ ...
 - Minitab软件是现代质量管理统计的领先者,全球六西格玛实施的共同语言,以无可比拟的强大功能和简易的可视化操作深受广大质量学者和统计专家的青睐。
		
Minitab软件是现代质量管理统计的领先者,全球六西格玛实施的共同语言,以无可比拟的强大功能和简易的可视化操作深受广大质量学者和统计专家的青睐. MINITAB 功能菜单包括:基础和高级统计工具: ...
 - java8 array、list操作 汇【4】)-  Java8 Lambda表达式 函数式编程
		
int tmp1 = 1; //包围类的成员变量 static int tmp2 = 2; //包围类的静态成员变量 //https://blog.csdn.net/chengwangbaiko/ar ...
 - java8  array、list操作 汇【2】)-  (Function,Consumer,Predicate,Supplier)应用
		
static class UserT { String name; public UserT(String zm) { this.name=zm; } public String getName() ...
 - java8 array、list操作 汇【3】)(-Java8新特性之Collectors 详解
		
//编写一个定制的收集器 public static class MultisetCollector<T> implements Collector<T, Multiset<T ...
 - Java8新特性 1——利用流和Lambda表达式操作集合
		
Java8中可以用简洁的代码来操作集合,比如List,Map,他们的实现ArrayList.以此来实现Java8的充分利用CPU的目标. 流和Lambda表达式都是Java8中的新特性.流可以实现对集 ...
 
随机推荐
- Linux系统基础5周入门精讲(Linux发展过程)
			
什么是操作系统 作为应用开发程序员,我们开发的软件都是应用软件,而应用软件必须运行于操作系统之上,操作系统则运行于硬件之上,应用软件是无法直接操作硬件的,应用软件对硬件的操作必须调用操作系统的接口,由 ...
 - 关于vector变量的size,是一个无符号数引发的bug。LeetCode 3 sum
			
class Solution { public: vector<vector<int>> threeSum(vector<int>& a) { vector ...
 - vue  监听state 任意值变化、监听mutations actions
			
// store.watch((state) => state.count + 1, (newCount) => { // console.log(' 监听') // }) // stor ...
 - spring Boot 上传文件,10天后,不能上传的bug
			
起因 公司研发人员 部署服务在阿里云 ecs 服务器; 上传文件过1周左右文件自动丢失; 排查思路: (1).查询tomcat 启动日志出现如下信息: java.io.IOException: The ...
 - Bash:精华
			
# 声明索引数组(以从0开始的整数做索引的数组).以下三种等效. declare -a array declare array=(this is numeric array ) array=(this ...
 - 一次docker中的nginx进程响应慢问题定位记录
			
有个ft测试的环境,其中nginx使用docker发布的.测试用例是curl的时候,没有获得nginx的响应. docker ps CONTAINER ID IMAGE COMMAND CREATED ...
 - 使用rgba设置输入框背景透明
			
项目中遇到要求输入框的背景设置透明度,但文字不受影响,如下图 输入框使用input标签 <input ref="searchText" type="search&q ...
 - Ubuntu网卡配置
			
目录 1.查看所有可用网卡 2.编辑配置文件 3.添加可用网卡信息 4.重启网络服务 5.查看网卡信息 1.查看所有可用网卡 $ ifconfig -a # -a display all interf ...
 - gitbash上使用tree
			
gitbash上使用tree vscode从cmd设置gitbash之后,想在使用windows下的tree命令发现运行不了,有两种解决方案. 1,在gitbash上cmd //c tree,就等同c ...
 - 开发JSP自定义标签
			
互联网上有很多种自定义标签,今天学的这种非常简单哟 1 编写一个普通类在类中定义一个经常使用得到的 函数 如public String toUpper(String str){ ...... } 2 ...