栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java Stream流常用方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java Stream流常用方法

文章目录

过滤分组分区拼接List map互转

list转mapmap转list 去重排序求和/极值统计求最大/最小值的对象平均值某个值的数量收集全部转大写查找与匹配跳过截断

过滤
//根据指定sn,过滤出符合的数据: List> deviceDataList
List> tempDeviceDataList = deviceDataList.stream().filter(map -> map.get("sn").toString().equals(sn)).collect(Collectors.toList());

//筛选出工资大于10000的职员
List newList = list.stream().filter(item -> {
			return item.getSalary().compareTo(new BigDecimal(10000)) > 0 && !item.getWorkType().equals("项目经理");
		}).collect(Collectors.toList());

分组
// 按照sn分组:  List> dataList
Map>> dataMap = dataList.stream().collect(Collectors.groupingBy(e -> e.get("sn") + ""));	

//按照职员部分分组: List list
Map> collect = list.stream().collect(Collectors.groupingBy(i -> i.getUnitName()));

//多条件分组
Map>> collect =list.stream().collect(Collectors.groupingBy(i -> i.getUnitName(),Collectors.groupingBy(i -> i.getWorkType())));

        //按年龄分组,年龄相同的是一组
        Map> 分组 = list.stream().collect(Collectors.groupingBy(Person::getAge));
 
        //按年龄分组后按工资分组,多级分组
        Map>> 多级分组 = list.stream().collect(Collectors.groupingBy(Person::getAge, Collectors.groupingBy(x -> {
            return x.getSalary() > 3000 ? "高" : "低";
        })));
 
// 分组排序 ,拿已经排好序的过来分组
linkedHashMap groupingByruleGroupList = ruleGroupList.stream().collect(Collectors.groupingBy(AttendanceRuleGroup::getCategory, linkedHashMap::new, Collectors.toList()));

// 分组排序,集合没排序,我们自己按我们想要的排序
 linkedHashMap groupingByruleGroupList = ruleGroupList.stream().sorted(Comparator.comparingLong(AttendanceRuleGroup::getSort).reversed()).collect(Collectors.groupingBy(AttendanceRuleGroup::getCategory, linkedHashMap::new, Collectors.toList()));


分区
//List list
//单层分区
Map> collect = list.stream().collect(Collectors.partitioningBy(i -> i.getId() == 1));

//分区 满足条件的一个区,不满足条件的一个区
        Map> collect1 = list.stream().collect(Collectors.partitioningBy(e -> e.getSalary() < 2000));

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

拼接
//将某个字段,按照某个字符串拼接:  List> 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> dataList = JdbcUtil.getJdbcTemplate().queryForList(dataSql, sns)

        List strs = Arrays.asList("a","b","cd");
 
        //连接所有内容
        String str = strs.stream().collect(Collectors.joining());
        System.out.println(str);
        //输出:abcd
 
        //连接所有内容,中间加一个逗号隔开
        String str1 = strs.stream().collect(Collectors.joining(","));
        System.out.println(str1);
        //输出:a,b,cd
 
        //连接所有内容,中间加一个逗号隔开,两边加上括号
        String str2 = strs.stream().collect(Collectors.joining(",","(",")"));
        System.out.println(str2);
        //输出:(a,b,cd)

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

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

去重
//去重之后进行拼接: List deviceNodeList
Srting deviceNodeStr = deviceNodeList.stream().distinct().collect(Collectors.joining("','"));
//直接去重返回list
// List deviceIdList
 List 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 list, s1-s2 升序   s2-s1降序
list.sort(Comparator.comparing(Employee::getSalary).reversed().thenComparing(Employee::getId).reversed());

求和/极值
//在egyList里面求cols的和
public static BigDecimal getSumBig(List> 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 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();

统计
//统计:和、数量、最大值、最小值、平均值: List 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());

求最大/最小值的对象
Optional optional = list.stream().collect(Collectors.maxBy(Comparator.comparing(Employee::getId)));
 if (optional.isPresent()) { // 判断是否有值
 		Employee user = optional.get();
 }
return optional.orElse(new Employee());

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

某个值的数量
//List list
Map collect = list.stream().collect(Collectors.groupingBy(i -> i.getSalary(),Collectors.counting()));

//List> egyList
long count = egyList.stream()
     .filter((Map m)->StringUtils.isNotEmpty(m.get(cols)+""))
     .map((Map m)->new BigDecimal(m.get(cols)+""))
     .count();

收集
        //取出所有年龄放到list集合中
        List toList = list.stream().map(Person::getAge)
                .collect(Collectors.toList());
 
        //取出所有年龄放到set集合中
        Set toSet = list.stream().map(Person::getAge)
                .collect(Collectors.toSet());
 
        //取出所有年龄放到hashSet集合中
        HashSet toHashSet = list.stream().map(Person::getAge)
                .collect(Collectors.toCollection(HashSet::new));
 
        //获取集合中元素总和
        Long count = list.stream().collect(Collectors.counting());
 
        //获取年龄平均值
        Double avg = list.stream().collect(Collectors.averagingInt(Person::getAge));
 
        //获取工资总和
        Double sum = list.stream().collect(Collectors.summingDouble(Person::getSalary));
 
        //获取工资最大值的人
        Optional max = list.stream().collect(Collectors.maxBy((p1, p2) -> Double.compare(p1.getSalary(), p2.getSalary())));
        System.out.println(max.get());
 
        //获取工资最小值的人
        Optional min = list.stream().collect(Collectors.minBy((p1, p2) -> Double.compare(p1.getSalary(), p2.getSalary())));
        System.out.println(min.get());
 
        //获取元素个数、总和、最小值、平均值、最大值
        DoubleSummaryStatistics collect = list.stream().collect(Collectors.summarizingDouble(Person::getSalary));
        System.out.println(collect);
        //输出结果:DoubleSummaryStatistics{count=5, sum=34024.000000, min=99.000000, average=6804.800000, max=9999.000000}

全部转大写
        List list = Arrays.asList("a","vvv","ddd");
 
        //中间操作:不会执行任何操作
        Stream stream = list.stream()
                .map(x -> x.toUpperCase());
 
        //终止操作:一次性执行全部内容,惰性求值
        stream.forEach(System.out::println);

查找与匹配
        List list = Arrays.asList(
                new Person(18,3939),
                new Person(38,9999),
                new Person(17,9999),
                new Person(19,9988),
                new Person(38,99)
        );
 
        //是否匹配所有元素 此处返回false
        boolean b = list.stream().allMatch(e -> e.getAge() == 18);
        System.out.println(b);
 
        //至少匹配一个元素,此处返回true
        boolean b1 = list.stream().anyMatch(e -> e.getAge() == 19);
        System.out.println(b1);
 
        //流中是否没有匹配元素,此处返回false
        boolean b2 = list.stream().noneMatch(e -> e.getAge() == 19);
        System.out.println(b2);
 
        //排序后获取第一个元素
        Optional first = list.stream().sorted((x, y) -> x.getAge().compareTo(y.getAge())).findFirst();
        System.out.println(first);
 
        //获取流中任意一个元素
        list.stream().findAny();
 
        //返回流中元素的总个数
        list.stream().count();
 
        //返回流中最大值 此处根据年龄比较
        Optional max = list.stream().max((x, y) -> x.getAge().compareTo(y.getAge()));
        System.out.println(max.get());
 
        //返回流中最小值 此处根据年龄比较
        Optional min = list.stream().min((x, y) -> x.getAge().compareTo(y.getAge()));
        System.out.println(min.get());
 
        //获取最小的年龄
        Optional age = list.stream().map(Person::getAge).min(Integer::compareTo);
        System.out.println(age.get());
 
 
        //获取一个并行流,并行流会使用多个线程操作流,stream()获取的是串行流,单个线程操作流
        list.parallelStream();
        
		//查找第一个元素
        Optional collect = menu.stream().filter(dish -> dish.getCalories() > 1000).findFrist();
       


跳过
        List list = Arrays.asList(1,2,3,4,5,6,7,8);
 
        //中间操作:不会执行任何操作
        Stream stream = list.stream()
                .skip(5);
 
        //终止操作:一次性执行全部内容,惰性求值
        stream.forEach(System.out::println);

截断
        List list = Arrays.asList(1,2,3,4,5,6,7,8);
 
        //中间操作:不会执行任何操作
        Stream stream = list.stream()
                .filter(e -> {
                    System.out.println("过滤 中间操作");
                    return e>3;
                })
                .limit(2);
 
        //终止操作:一次性执行全部内容,惰性求值
        stream.forEach(System.out::println);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/777106.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号