stream 进行排序、分组、多级分组、交集、并集、差集等

package com.al.admin.utils;

import cn.hutool.core.util.ObjectUtil;
import lombok.Data;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 测试
 */
public class StreamUtil {

    public static void main(String[] args) {

        List<Student> students = new ArrayList<>();
        for(int i=0; i<5 ;i++) {
            Student student = new StreamUtil().new Student();
            student.setId(i+"");
            if(i > 2) {
                student.setAge(1);
            } else {
                student.setAge(2);
            }
            if(i > 3) {
                student.setName("zhangsan");
            } else if(i == 0) {
                student.setName(null);
            } else {
                student.setName("lisi");
            }
            student.setMoney(i);
            student.setCreatedDate(null);
            students.add(student);
        }
//多级进行分组 当然也可以进行其他的操作
        Map<String, Map<Integer, List<Student>>> collectq = students.stream()
                .collect(Collectors.groupingBy(x -> StringUtils.isEmpty(x.getName()) ? "" : x.getName(), Collectors.groupingBy(Student::getAge)));
        System.out.println("collectq:" + collectq);

        SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, List<Student>> groupBy = students.stream().collect(Collectors.groupingBy(a -> sm.format(a.getCreatedDate())));
        System.out.println("==============");
        System.out.println(groupBy);


        /**
         * 条件过滤
         */
        System.out.println("条件过滤==============");
        System.out.println("student.getAge() >1 ==============");
        List<Student> collect = students.stream().filter(student -> student.getAge() > -1).collect(Collectors.toList());
        System.out.println(collect);

        /**
         * 正序排列
         */
        System.out.println("正序排列==============");
        collect = collect.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
        System.out.println(collect);

        /**
         * 倒序排列
         */
        System.out.println("倒序排列==============");
        collect = collect.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
        System.out.println(collect);

        /**
         * string 类型的字段 倒序排列
         */
        System.out.println("string 类型的字段进行倒序排序 ==============");
        collect = collect.stream().sorted(Comparator.comparing(Student::getId).reversed()).collect(Collectors.toList());
        System.out.println(collect);


        /**
         * string 类型的字段 进行截取 倒序排列
         */
        System.out.println("string 类型的字段进行倒序排序 ==============");
        collect = collect.stream().sorted((o1,o2) -> {
            try {
                return Integer.parseInt(o2.getName().split("-")[1].substring(0,5)) - Integer.parseInt(o1.getName().split("-")[1].substring(0,5));
            } catch (Exception e){
                e.printStackTrace();
            }
            return 0;
        }).collect(Collectors.toList());
        System.out.println(collect);


        /**
         * 多字段倒序排序
         */
        System.out.println("多字段倒序排序 ==============");
        collect = collect.stream().sorted(Comparator.comparing(Student::getAge).thenComparing(Student::getId).reversed()).collect(Collectors.toList());
        System.out.println(collect);

        /**
         * 多字段条件
         */
        System.out.println("age大于20 money大于3000的数据==============");
        Predicate<Student> predicate1 = student -> student.getAge()>20;
        Predicate<Student> predicate2 = student -> student.getMoney()>3000;
        List<Student> collect1 = collect.stream().filter(predicate1.and(predicate2)).collect(Collectors.toList());
        System.out.println(collect1);

        /**
         * 两个集合差集 、 并集 、 交集
         * 集合 students 、 collect
         */
        System.out.println("两个集合差集");
        Predicate<Student> predicate =
                user -> collect1.stream()
                        .noneMatch(user1 -> (user.getId()).equalsIgnoreCase(user1.getId()));
        collect = students.stream().filter(predicate).collect(Collectors.toList());
        System.out.println("students - collect1的差集  注意 集合a对集合b之间的差集 和 集合b对集合a之间的差集 不一样");
        System.out.println(collect);

        System.out.println("两个集合交集");
        Predicate<Student> predicate3 =
                user -> collect1.stream()
                        .anyMatch(user1 -> (user.getId()).equalsIgnoreCase(user1.getId()));
        collect = students.stream().filter(predicate3).collect(Collectors.toList());
        System.out.println("students - collect1的交集");
        System.out.println(collect);

        System.out.println("两个集合并集");
        List<Student> collect2 = students.parallelStream().collect(Collectors.toList());
        List<Student> collect3 = collect1.parallelStream().collect(Collectors.toList());
        collect2.addAll(collect3);
        List<Student> collect4 = collect2.stream().distinct().collect(Collectors.toList());
        System.out.println(collect4);

        System.out.println("list 转 map");
        System.out.println("key是list对象中id,value是list对象中的年龄");
        Map<String, Integer> map = students.stream().collect(Collectors.toMap(Student::getId, Student::getAge));
        System.out.println(map);

        System.out.println("key是list对象中id,value是list对象");
        Map<String, Student> map1 = students.stream().collect(Collectors.toMap(Student::getId, student -> student));
        System.out.println(map1);
        System.out.println("key是list对象中id,value是list对象 另一种写法");
        Map<String, Student> map2 = students.stream().collect(Collectors.toMap(Student::getId, Function.identity()));
        System.out.println(map2);

        System.out.println("key是对象中的某个属性值,value是对象本身,当key冲突时选择第二个key值覆盖第一个key值。");
        Map<String, Student> map3 = students.stream().collect(Collectors.toMap(Student::getId, Function.identity(), (oldValue, newValue) -> newValue));
        System.out.println(map3);

        System.out.println("map 转 list");
        List<String> collect5 = map3.keySet().stream().collect(Collectors.toList());
        List<Student> collect6 = map3.values().stream().collect(Collectors.toList());
        System.out.println("map的key转list::"+collect5);
        System.out.println("map的value转list::"+collect6);


        List<Student> lst = map.entrySet().stream().map(c -> {
            Student student = new StreamUtil().new Student();
            student.setId(c.getKey());
            student.setAge(c.getValue());
            return student;
        }).collect(Collectors.toList());
        System.out.println("通过map的key,value转对象集合");
        System.out.println(lst);

    }

    @Data
    public class Student {

        private String id;
        private int age;
        private double money;
        private String name;
        private Date createdDate;

        public Student(){

        }
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值