1.jdk8中Stream基础操作

导读:本篇文章讲解 1.jdk8中Stream基础操作,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

Java8快速实现List转map 、分组、过滤等操作
定义1个Apple对象:

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);

1、分组
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}]}

2、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}}

 Map<Integer,String> userMap = userList.stream().collect(Collectors.toMap(User::getId,User::getName));


3、过滤Filter

从集合中过滤出来符合条件的元素:
//过滤出符合条件的数据
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 totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
System.err.println("totalMoney:"+totalMoney);  //totalMoney:17.48

5.查找流中最大 最小值

Collectors.maxBy 和 Collectors.minBy 来计算流中的最大或最小值。
Optional<Dish> maxDish = Dish.menu.stream().
      collect(Collectors.maxBy(Comparator.comparing(Dish::getCalories)));
maxDish.ifPresent(System.out::println);
 
Optional<Dish> minDish = Dish.menu.stream().
      collect(Collectors.minBy(Comparator.comparing(Dish::getCalories)));
minDish.ifPresent(System.out::println);

6.去重

import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

// 根据id去重
List<Person> unique = appleList.stream().collect(
 collectingAndThen(
      toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))), ArrayList::new)
  );

集中:

        //获取所有年龄20岁以下的学生
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student(1, 19, "张三", "M", true));
        students.add(new Student(1, 18, "李四", "M", false));
        students.add(new Student(1, 21, "王五", "F", true));
        students.add(new Student(1, 20, "赵六", "F", false));
        //filter:过滤小于20岁
        List<Student> list = students.stream().filter(student -> student.getStudentAge() < 20).collect(Collectors.toList());
        //获取所有学生的姓名,并形成一个新的集合
        List<String> collect = students.stream().map(Student::getStudentName).collect(Collectors.toList());
        //判断流中是否至少存在一个符合条件的元素
        if (students.stream().anyMatch(student -> student.getStudentAge() < 20)) {
            System.out.println("集合中有年龄小于20的学生");
        } else {
            System.out.println("集合中没有年龄小于20的学生");
        }
        if (students.stream().allMatch(student -> student.getStudentAge() < 20)) {
            System.out.println("集合所有学生的年龄都小于20");
        } else {
            System.out.println("集合中有年龄大于20的学生");
        }
        //findAny用于获取流中随机的某一个元素,并且利用短路在找到结果时,立即结束
        Optional<Student> student1 = students.stream().filter(student -> student.getStudentSix().equals("F")).findAny();
        System.out.println(student1.toString());

        //通过counting()统计集合总数  方法一
        Long colle = students.stream().collect(Collectors.counting());
        System.out.println(colle);
        //结果 4

        //通过count()统计集合总数  方法二
        long count = students.stream().count();
        System.out.println(count);
        //结果 4

        //通过maxBy求最大值
        Optional<Student> collect1 = students.stream().collect(Collectors.maxBy(Comparator.comparing(Student::getStudentAge)));
        if (collect1.isPresent()) {
            System.out.println(collect1);
        }
        //结果 Optional[Student{id=1, age=21, name='王五', sex='F', isPass=true}]

        //通过max求最大值
        Optional<Student> max = students.stream().max(Comparator.comparing(Student::getStudentAge));
        if (max.isPresent()) {
            System.out.println(max);
        }
        //结果  Optional[Student{id=1, age=21, name='王五', sex='F', isPass=true}]

        //通过minBy求最小值
        Optional<Student> collect2 = students.stream().collect(Collectors.minBy(Comparator.comparing(Student::getStudentAge)));
        if (collect2.isPresent()) {
            System.out.println(collect2);
        }
        //结果  Optional[Student{id=1, age=18, name='李四', sex='M', isPass=false}]

        //通过min求最小值
        Optional<Student> min = students.stream().min(Comparator.comparing(Student::getStudentAge));
        if (min.isPresent()) {
            System.out.println(min);
        }
        //结果  Optional[Student{id=1, age=18, name='李四', sex='M', isPass=false}]

        //通过summingInt()进行数据汇总
        Integer collect3 = students.stream().collect(Collectors.summingInt(Student::getStudentAge));
        System.out.println(collect3);
        //结果 78

        //通过averagingInt()进行平均值获取
        Double collect4 = students.stream().collect(Collectors.averagingInt(Student::getStudentAge));
        System.out.println(collect4);
        //结果 19.5

        //通过joining()进行数据拼接
        String collect5 = students.stream().map(Student::getStudentName).collect(Collectors.joining("-"));
        System.out.println(collect5);
        //结果 张三-李四-王五-赵六

        //复杂结果的返回
        IntSummaryStatistics collect6 = students.stream().collect(Collectors.summarizingInt(Student::getStudentAge));
        double average = collect6.getAverage();
        long sum = collect6.getSum();
        long count1 = collect6.getCount();
        int max1 = collect6.getMax();
        int min1 = collect6.getMin();

        //通过性别对学生进行分组
        Map<String, List<Student>> groupCollect = students.stream().collect(Collectors.groupingBy(Student::getStudentSix));

        //现根据是否新学生对学生分组,再根据性别分组
        Map<String, Map<Boolean, List<Student>>> col = students.stream().collect(Collectors.groupingBy(Student::getStudentSix, Collectors.groupingBy(Student::getNewStudent)));
       //{F={false=[Student(studentId=1, studentAge=20, studentName=赵六, studentSix=F, newStudent=false)], true=[Student(studentId=1, studentAge=21, studentName=王五, studentSix=F, newStudent=true)]}, M={false=[Student(studentId=1, studentAge=18, studentName=李四, studentSix=M, newStudent=false)], true=[Student(studentId=1, studentAge=19, studentName=张三, studentSix=M, newStudent=true)]}}
        System.out.println(col.toString());


        //根据年龄进行分组,获取并汇总人数
        Map<Integer, Long> coll2e= students.stream().collect(Collectors.groupingBy(Student::getStudentAge, Collectors.counting()));
        System.out.println(coll2e);

        //要根据年龄与是否新生进行分组,并获取每组中年龄的学生
        Map<Integer, Map<Boolean, Student>> collect33 = students.stream().collect(Collectors.groupingBy(Student::getStudentAge, Collectors.groupingBy(Student::getNewStudent,
                Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(Student::getStudentAge)), Optional::get))));
       //{18={false=Student(studentId=1, studentAge=18, studentName=李四, studentSix=M, newStudent=false)}, 19={true=Student(studentId=1, studentAge=19, studentName=张三, studentSix=M, newStudent=true)}, 20={false=Student(studentId=1, studentAge=20, studentName=赵六, studentSix=F, newStudent=false)}, 21={true=Student(studentId=1, studentAge=21, studentName=王五, studentSix=F, newStudent=true)}}
        System.out.println(collect33.toString());

        List<Integer> integers = Arrays.asList(1, 2, 3, 4, 4, 5, 5, 6, 7, 8, 2, 2, 2, 2);
        //distinct实现数据去重
        List<Integer> distinct = integers.stream().distinct().collect(Collectors.toList());
        //基于limit()实现数据截取  :获取数组的前五位
        List<Integer> limit = integers.stream().limit(5).collect(Collectors.toList());
        //从集合第三个开始截取5个数据
        List<Integer> skip = integers.stream().skip(3).limit(5).collect(Collectors.toList());
        skip.forEach(integer -> System.out.print(integer + " "));
        System.out.println("");
        //先从集合中截取5个元素,然后取后3个
        List<Integer> coll = integers.stream().limit(5).skip(2).collect(Collectors.toList());
        coll.forEach(integer -> System.out.print(integer + " "));
        System.out.println("");
        //对集合中的元素求和
        Integer reduce = integers.stream().reduce(0, Integer::sum);
        System.out.println(reduce);

        /**
         * 获取集合中的最大值
         */
        //方法一
        Optional<Integer> max11 = integers.stream().reduce(Integer::max);
        if (max11.isPresent()) {
            System.out.println(max11);
        }
        //方法二
        Optional<Integer> max22 = integers.stream().max(Integer::compareTo);
        if (max22.isPresent()) {
            System.out.println(max22);
        }

        /**
         * 获取集合中的最小值
         */
        //方法一
        Optional<Integer> min111 = integers.stream().reduce(Integer::min);
        if (min111.isPresent()) {
            System.out.println(min111);
        }

        //方法二
        Optional<Integer> min222 = integers.stream().min(Integer::compareTo);
        if (min222.isPresent()) {
            System.out.println(min222.get());
        }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/65806.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!