ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

JDK1.8 Steam()常用方法

2021-12-12 02:31:50  阅读:341  来源: 互联网

标签:JDK1.8 Collectors stream List list 常用 collect Steam BigDecimal


Stream的使用可极大的减少sql的复杂度和对数据库的访问压力,我们可以用sql将数据一次性全部取出来,根据我们的实际需要,去组织我们需要的数据。

分组

// 按照sn分组:  List<Map<String, Object>> dataList
Map<String, List<Map<String, Object>>> dataMap = dataList.stream().collect(Collectors.groupingBy(e -> e.get("sn") + ""));	
//按照职员部分分组: List<Employee> list
Map<String, List<Employee>> collect = list.stream().collect(Collectors.groupingBy(i -> i.getUnitName()));
//多条件分组
Map<String, Map<String,List<Employee>>> collect =list.stream().collect(Collectors.groupingBy(i -> i.getUnitName(),Collectors.groupingBy(i -> i.getWorkType())));

过滤

//根据指定sn,过滤出符合的数据: List<Map<String, Object>> deviceDataList
List<Map<String, Object>> tempDeviceDataList = deviceDataList.stream().filter(map -> map.get("sn").toString().equals(sn)).collect(Collectors.toList());
//筛选出工资大于10000的职员
List<Employee> newList = list.stream().filter(item -> {
			return item.getSalary().compareTo(new BigDecimal(10000)) > 0 && !item.getWorkType().equals("项目经理");
		}).collect(Collectors.toList());

List和Map互转

list转map

// (k1,k2)->k2 避免键重复 k1-取第一个数据;k2-取最后一条数据
//key和value,都可以根据传入的值返回不同的Map
Map<String, String> deviceMap = hecmEnergyDevicesList.stream().collect(Collectors.toMap(i -> i.getDeviceNum(), j -> j.getDeviceName(), (k1, k2) -> k1));
//
Map<String, Object> map = list.stream()
				.collect(Collectors.toMap(i -> i.getEmpName() + i.getUnitName(), j -> j, (k1, k2) -> k1));

map转list

//在.map里面构造数据 return什么数据就转成什么类型的list
List<Employee> collect = map.entrySet().stream().map(item -> {
			Employee employee = new Employee();
			employee.setId(item.getKey());
			employee.setEmpName(item.getValue());
			return employee;
		}).collect(Collectors.toList());

求和/极值

//在egyList里面求cols的和
public static BigDecimal getSumBig(List<Map<String,Object>> egyList, String cols){
        BigDecimal consuBig = egyList.stream()
                .filter((Map m)->StringUtils.isNotEmpty(m.get(cols)+"") && !"null".equals(String.valueOf(m.get(cols)))
                        && !"-".equals(String.valueOf(m.get(cols))))
                .map((Map m)->new BigDecimal(m.get(cols)+""))
                .reduce(BigDecimal.ZERO,BigDecimal::add);
        return consuBig;
}
//List<Employee> list
//Bigdecimal求和/极值: 
BigDecimal sum = list.stream().map(Employee::getSalary).reduce(BigDecimal.ZERO,BigDecimal::add);
BigDecimal max = list.stream().map(Employee::getSalary).reduce(BigDecimal.ZERO,BigDecimal::max);
//基本数据类型求和/极值:
Integer sum = list.stream().mapToInt(Employee::getId).sum();
OptionalInt optionalMax = list.stream().mapToInt(Employee::getId).max();
optionalMax.getAsInt();

求最大/最小值的对象

Optional<Employee> optional = list.stream().collect(Collectors.maxBy(Comparator.comparing(Employee::getId)));
 if (optional.isPresent()) { // 判断是否有值
 		Employee user = optional.get();
 }
return optional.orElse(new Employee());

去重

//去重之后进行拼接: List<String> deviceNodeList
Srting deviceNodeStr = deviceNodeList.stream().distinct().collect(Collectors.joining("','"));
//直接去重返回list
// List<String> deviceIdList
 List<String> deviceIdList = deviceIdList.stream().distinct().collect(Collectors.toList());

排序

//按照时间排序 1升 -1降
Collections.sort(listFast, (p1, p2) -> {
     return String.valueOf(p1.get("time")).compareTo(p2.get("time") + "");
});
// s1-s2 升序   s2-s1降序
Collections.sort(list,(s1,s2) -> s1.getSalary().compareTo(s2.getSalary()));
//多条件排序: List<Employee> list, s1-s2 升序   s2-s1降序
list.sort(Comparator.comparing(Employee::getSalary).reversed().thenComparing(Employee::getId).reversed());

拼接

//将某个字段,按照某个字符串拼接:  List<Map<String, Object>> deviceMapList 
String sns = deviceMapList.stream()
     	.map((m)->m.get("sn")+"").collect(Collectors.joining(","));
//使用场景很多,在sql里面用于组织in的值.比如:
SELECT sn,time,value FROM electric_real_time WHERE FIND_IN_SET(sn,?)
List<Map<String, Object>> dataList = JdbcUtil.getJdbcTemplate().queryForList(dataSql, sns)

统计

//统计:和、数量、最大值、最小值、平均值: List<Employee> list
IntSummaryStatistics collect = list.stream().collect(Collectors.summarizingInt(Employee::getId));
System.out.println("和:" + collect.getSum());
System.out.println("数量:" + collect.getCount());
System.out.println("最大值:" + collect.getMax());
System.out.println("最小值:" + collect.getMin());
System.out.println("平均值:" + collect.getAverage());

平均值

OptionalDouble average = list.stream().mapToInt(Employee::getId).average();
average.getAsDouble();

某个值的数量

//List<Employee> list
Map<BigDecimal, Long> collect = list.stream().collect(Collectors.groupingBy(i -> i.getSalary(),Collectors.counting()));
//List<Map<String,Object>> egyList
long count = egyList.stream()
     .filter((Map m)->StringUtils.isNotEmpty(m.get(cols)+""))
     .map((Map m)->new BigDecimal(m.get(cols)+""))
     .count();

分区

//List<Employee> list
//单层分区
Map<Boolean, List<Employee>> collect = list.stream().collect(Collectors.partitioningBy(i -> i.getId() == 1));
//多层分区
Map<Boolean, Map<Boolean,List<Employee>>> collect = list.stream().collect(Collectors.partitioningBy(i -> i.getId() == 1,Collectors.partitioningBy(i -> i.getSalary().compareTo(new BigDecimal(20000)) == 0)));

 

标签:JDK1.8,Collectors,stream,List,list,常用,collect,Steam,BigDecimal
来源: https://www.cnblogs.com/21-Gram/p/15678037.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有