Bootstrap

Stream流的常用方法大全

目录

前言

1. forEach遍历

2. filter过滤

3. distinct去重

4. limit截取

5. skip跳过

6.排序sorted

7.最值max,min

8. 统计reduce

9. List结构转换Map结构

10. List对象转List

11. List对象转List

总结


前言

毕业入职工作后开始接触Stream流,觉得挺方便的,尽可能全面的记录一下Stream流的方法。

1. forEach遍历


        forEach:该方法接收一个Consumer接口函数,将每一个流元素交给该函数处理
        forEach方法:用来遍历流中的数据
        注:是一个终结方法,遍历之后就不能继续调用Stream流中的其他方法

public class Stream_ForEach {
    public static void main(String[] args) {
    //获取一个Stream流
    Stream<String>stream= Stream.of("张三","李四","王五","赵六");
        //使用Stream流的方法forEach对stream流中的数据遍历
        stream.forEach((String name)->{
            System.out.println(name);
        });
    }
}

2. filter过滤

        filter:用于对Stream流中的数据进行过滤
        filter(Predicate<? super T>predicate)
        filter方法的参数Predicate是一个函数式接口,可以使用lambda表达式
        Predicate中的抽象方法
        boolean test(T t)

public class Stream_filter {
    public static void main(String[] args) {
        //创建一个Stream流
        Stream<String> stream = Stream.of("张三", "李四", "王五", "赵六1", "刘老七");

        //单条件过滤
        Stream<String> stream1 = stream.filter((String name) -> {
            return name.startsWith("刘");
        });

        //多条件过滤
        List<String> stream2 = stream.filter((String name) -> {
            if(name.length()>=3 && name.equals("刘老七")){
                return true;
            }
                return false;
        }).collect(Collectors.toList);

        //遍历stream1
        stream1.forEach((name)-> System.out.println(name));
        
        //输出stream2
        System.out.println(stream2)
        
    }
}

3. distinct去重

public class Stream_distinct {
    public static void main(String[] args) {
        //创建一个Stream流
        Stream<String> stream = Stream.of("张三", "张三","张三","李四", "王五", "赵六1", "刘老七");
        //去重
        List<String> stream1 = stream().distinct().collect(Collectors.toList());
        //输出stream1
        System.out.println(stream1)
    }
}

4. limit截取

        limit:用于截取流中的元素
        limit可以对流进行截取,只取用前n个
        limit(long maxSize);
        参数是一个long型,如果集合当前长度大于参数则进行截取,否则不进行操作
        limit是一个延迟方法,可以继续使用Stream流方法

public class Stream_limit {
    public static void main(String[] args) {
        //创建一个Stream流
        Stream<String> stream = Stream.of("张三", "张三","张三","李四", "王五", "赵六1", "刘老七");
        //去重
        List<String> list = stream().distinct().collect(Collectors.toList());
        //截取去重后的前2个元素
        list = list.stream().limit(2).collect(Collectors.toList();
        //输出stream1
        System.out.println(list)
    }
}

5. skip跳过

        skip方法:用于跳过元素
        skip(long n)
        如果流的当前长度大于n,则跳过前n个,否则将会得到一个长度为0的空流

public class Stream_skip {
    public static void main(String[] args) {
        //创建一个Stream流
        Stream<String> stream = Stream.of("张三", "张三","张三","李四", "王五", "赵六1", "刘老七");
        //去重
        List<String> list = stream().distinct().collect(Collectors.toList());
        //跳过去重后的前2个元素
        list = list.stream().skip(2).collect(Collectors.toList());
        //输出stream1
        System.out.println(list)
    }
}

6.排序sorted

public class Stream_sorted {
    public static void main(String[] args) {
        List<Test> list = new ArrayList<>();
        list.add(new Test("张三",23,new BigDecimal("3000"),new BigDecimal("1.1")));
        list.add(new Test("李四",24,new BigDecimal("2800"),new BigDecimal("1.2")));
        list.add(new Test("王五",22,new BigDecimal("3200"),new BigDecimal("1.3")));

        //根据年龄从大到小排序
        list = list.stream()
                   .sorted(Comparator.comparing(Test::getAge).reversed())
                   .collect(Collectors.toList());
        list.forEach(System.out::println);


    }
}

7.最值max,min

public class Stream_max_min {
    public static void main(String[] args) {
        List<Test> list = new ArrayList<>();
        list.add(new Test("张三",23,new BigDecimal("3000"),new BigDecimal("1.1")));
        list.add(new Test("李四",24,new BigDecimal("2800"),new BigDecimal("1.2")));
        list.add(new Test("王五",22,new BigDecimal("3200"),new BigDecimal("1.3")));
        
        //获取年龄最大的人
        Test maxPeople = list.stream().max(Comparator.companing(Test::getAge)).get();
      
        //获取年龄最小的人
        Test minPeople = list.stream().min(Comparator.companing(Test::getAge)).get();

    }
}

8. 统计reduce

public class Stream_reduce {
    public static void main(String[] args) {
        List<Test> testList = new ArrayList<Test>();
        testList.add(new Test("小明",23,new BigDecimal("3000"),new BigDecimal("1.1")));
        testList.add(new Test("小红",24,new BigDecimal("2800"),new BigDecimal("1.2")));
        testList.add(new Test("小兰",22,new BigDecimal("3200"),new BigDecimal("1.3")));

        //统计年龄总和
        int totalAge =testList.stream().mapToInt(Test::getAge).sum();

        //统计工资总和
        BigDecimal totalSalary = testList.stream().map(Test::getSalary)

        //统计工资乘以各自系数的总和(向上保留两位)
        BigDecimal totalRatioSalary = testList.stream()
                                              .map(s->s.getSalary()
                                              .multiply(s.getRatio())
                                              .setScale(2,BigDecimal.ROUND_HALF_UP))
                                              .reduce(BigDecimal.ZERO,BigDecimal::add);
    }
}

9. List结构转换Map结构

public class Stream_List_Map {
    public static void main(String[] args) {
        List<Test> testList = new ArrayList<Test>();
        testList.add(new Test("张三",23,new BigDecimal("3000"),new BigDecimal("1.1")));
        testList.add(new Test("李四",24,new BigDecimal("2800"),new BigDecimal("1.2")));
        testList.add(new Test("王五",22,new BigDecimal("3200"),new BigDecimal("1.3")));
        //根据姓名转map,map的key为name
        Map<String, Test> nameMap= testList.stream().collect(Collectors.toMap(Test::getName, Test -> Test);
        System.out.println(map);
    }
}

10. List<Object>对象转List<String>


public class Stream_object_string {
    public static void main(String[] args) {
        List<Test> testList = new ArrayList<Test>();
        testList.add(new Test("张三",23,new BigDecimal("3000"),new BigDecimal("1.1")));
        testList.add(new Test("李四",24,new BigDecimal("2800"),new BigDecimal("1.2")));
        testList.add(new Test("王五",22,new BigDecimal("3200"),new BigDecimal("1.3")));
        //获取姓名集合
        List<String> nameList = testList.stream().map(Test::getName()).collect(Collectors.toList());
        System.out.println("value:"+nameList);
    }
}

11. List<Object>对象转List<Object>

public class Stream_object_object {
    public static void main(String[] args) {
        List<People> peopleList = new ArrayList<People>();
        peopleList.add(new People("张三",23,new BigDecimal("3000"),new BigDecimal("1.1")));
        peopleList.add(new People("李四",24,new BigDecimal("2800"),new BigDecimal("1.2")));
        peopleList.add(new People("王五",22,new BigDecimal("3200"),new BigDecimal("1.3")));
        //对象转对象
        List<Student> studentList = peopleList.stream().map(s->{
            return new Student(s.getName(),s.getAge());
        }).collect(Collectors.toList());
        System.out.println("value:"+studentList);
    }
}

总结

;