java8 Stream 流

java8之前对数据的处理大多都在sql中进行,java8之后,就可以使用Stream来处理List集合里的数据。这样我们可以快速的过滤出我们所需要的数据。

----------------------------------------------------------------------------------------

package com.example.java8.mapper;
/**
 * @Author peter
 * 模拟实体类,公司人员信息
 */
public class Employee {
    /**
     * 人员id
     */
    private int id;
    /**
     * 姓名
     */
    private String name;
    /**
     * 年龄
     */
    private int age;
    /**
     * 工资收入
     */
    private Double salary;
    /**
     * 状态
     */
    private Status status;

    public Employee(int id, String name, int age, Double salary, Status status) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
        this.status = status;
    }

    public Employee() {

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Employee employee = (Employee) o;

        if (age != employee.age) return false;
        if (!name.equals(employee.name)) return false;
        if (!salary.equals(employee.salary)) return false;
        return status == employee.status;
    }

    @Override
    public int hashCode() {
        int result = name.hashCode();
        result = 31 * result + age;
        result = 31 * result + salary.hashCode();
        result = 31 * result + status.hashCode();
        return result;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                ", status=" + status +
                '}';
    }

    public enum Status {
        FREE, BUSY, VOCATION;
    }
}

------------------------------------------------------------------------------------

package com.example.java8.java8test;

import com.example.java8.mapper.Employee;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 一、Stream API 的操作步骤:
 *
 * 1. 创建 Stream
 *
 * 2. 中间操作
 *
 * 3. 终止操作(终端操作)
 * 注意:流进行了终止操作后,不能再次使用
 */
public class StreamTest {
     /**
     * 当前公司的员工信息
     */
     private  List<Employee> employees = Arrays.asList(
            new Employee(1,"sun",25,5000.0, Employee.Status.BUSY),
            new Employee(3,"tina",22,4500.0, Employee.Status.FREE),
            new Employee(4,"jack",66,9900.0, Employee.Status.VOCATION),
            new Employee(5,"peter",77,4509.99, Employee.Status.BUSY),
            new Employee(6,"lose",10,888.8, Employee.Status.BUSY),
             new Employee(11,"lose",10,888.8, Employee.Status.BUSY),
             new Employee(12,"lose",10,888.8, Employee.Status.BUSY),
             new Employee(13,"lose",10,888.8, Employee.Status.BUSY),
             new Employee(7,"rise",39,682.2, Employee.Status.VOCATION),
             new Employee(8,"dex",56,15000.0, Employee.Status.VOCATION),
             new Employee(9,"great",12,3000.98, Employee.Status.FREE),
             new Employee(10,"lady",33,26859.2, Employee.Status.FREE)
    );
    /**
     * 创建Stream
     */
    @Test
    public void test8(){
        //1. Collection 提供了两个方法  stream() 与 parallelStream()
        List<String> list = new ArrayList<>();
        Stream<String> stream = list.stream(); //获取一个顺序流
        Stream<String> parallelStream = list.parallelStream(); //获取一个并行流
        //2. 通过 Arrays 中的 stream() 获取一个数组流
        Integer[] nums = new Integer[10];
        Stream<Integer> stream1 = Arrays.stream(nums);
        //3. 通过 Stream 类中静态方法 of()
        Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6);
        stream2.forEach(System.out::print);
        System.out.println();
        //4. 创建无限流
        //迭代
        Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10);
        stream3.forEach(System.out::println);
        //生成
        Stream<Double> stream4 = Stream.generate(Math::random).limit(2);
        stream4.forEach(System.out::println);
    }
    /**
     * 直接输出
     * 筛选与切片
     * filter——接收 Lambda , 从流中排除某些元素。
     * limit——截断流,使其元素不超过给定数量。
     * skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
     * distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
     */
    @Test
    public void test1(){
         employees.stream().distinct()
                 .sorted(new Comparator<Employee>() {//按照年龄排序,正序
                         @Override
                         public int compare(Employee o1, Employee o2) {
                             return o1.getAge()-o2.getAge();
                         }
                     })
                 .filter(a->a.getSalary()>3000)//选出工资3K以上的
                 .limit(5)    //选出前5个人
                 .skip(2)    //前两人不要
                 .forEach(System.out::println);
     }
    /**
     * 去重
     */
    @Test
    public void test6(){
        employees.stream().distinct().forEach(System.out::println);
    }
    /**
     * 惰性求值
     */
    @Test
    public void test7(){
        //所有的中间操作不会做任何的处理
        Stream<Employee> stream = employees.stream().distinct().skip(3).limit(5).sorted(new Comparator<Employee>() {
            @Override
            public int compare(Employee o1, Employee o2) {
                System.out.println("排序");
                return o1.getAge()-o2.getAge();
            }
        });
        //只有当做终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值”
        stream.forEach(System.out::println);
    }


    /**
     * 返回List集合
     */
    @Test
    public void test2(){
        List<Employee> collect = employees.stream().limit(5).collect(Collectors.toList());
        for(Employee employee:collect){
            System.out.println(employee.toString());
        }
    }

    /**
     * 获取公司中年龄最大的
     */
    @Test
    public void test3(){
        Optional<Employee> max = employees.stream().max((x,y)-> x.getAge()-y.getAge());
        Employee employee = max.get();
        System.out.println(employee.toString());
    }

    /**
     *数组排序
     */
    @Test
    public void test4(){
        List<Integer> list = Arrays.asList(1,65,898,5,65,32,3556,23,0,12,45,6596,546,235,56,-99,-89,-9,-56,-652,-32);
        list.stream().sorted(Integer::compare).forEach(System.out::println);//数组排序
        list.stream().sorted().forEach(System.out::println);//排序;
        System.out.println("max::"+list.stream().max(Integer::compare).get());
        System.out.println("min::"+list.stream().min(Integer::compare).get());
    }
    /**
     *公司人员自然排序
     * sorted()——自然排序
     * sorted(Comparator com)——定制排序
     */
    @Test
    public void test9(){
        employees.stream().map(Employee::getName).sorted().forEach(System.out::println);
    }
    /**
     * 映射
     * map——接收 Lambda , 将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,
     * 并将其映射成一个新的元素。
     * flatMap——接收一个函数作为参数,将流中的每个值都换成另一个流,
     * 然后把所有流连接成一个流
     */
    @Test
    public void test10(){
        List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
        Stream<Stream<Character>> map = strList.stream().map(StreamTest::filterCharacter);
        map.forEach(a -> a.forEach(System.out::println));
        System.out.println("<<<<<<<<<<>>>>>>>>>>>>>");
        Stream<Character> flatMap = strList.stream().flatMap(StreamTest::filterCharacter);
        flatMap.forEach(System.out::println);

    }
    public static Stream<Character> filterCharacter(String str){
        List<Character> list = new ArrayList<>();
        for (Character ch : str.toCharArray()) {
            list.add(ch);
        }
        return list.stream();
    }
    /**
     * allMatch——检查是否匹配所有元素 -------返回Boolean值
     * anyMatch——检查是否至少匹配一个元素 -------返回Boolean值
     * noneMatch——检查是否没有匹配的元素 -------返回Boolean值
     * findFirst——返回第一个元素
     * findAny——返回当前流中的任意元素
     * count——返回流中元素的总个数
     * max——返回流中最大值
     * min——返回流中最小值
     */
    @Test
    public void test5(){
        boolean b = employees.stream().allMatch(x -> x.getStatus().equals(Employee.Status.BUSY));
        System.out.println("allMatch::"+b);
        boolean c = employees.stream().anyMatch(x -> x.getStatus().equals(Employee.Status.BUSY));
        System.out.println("anyMatch::"+c);
        boolean d = employees.stream().noneMatch(x -> x.getStatus().equals(Employee.Status.BUSY));
        System.out.println("noneMatch::"+d);
        Optional<Employee> first = employees.stream().sorted((x,y)->y.getAge()-x.getAge()).findFirst();
        System.out.println("findFirst::"+first.get().toString());
        Optional<Employee> first1 = employees.stream().sorted((x,y)->x.getAge()-y.getAge()).findFirst();
        System.out.println("findFirst::"+first1.get().toString());
        Optional<Employee> findAny = employees.stream().sorted((x,y)->y.getAge()-x.getAge()).findAny();
        System.out.println("findAny::"+findAny.get().toString());
        long count = employees.stream().count();
        System.out.println("count::"+count);
        Optional<Employee> max = employees.stream().max((x, y) -> Double.compare(x.getSalary(), y.getSalary()));
        System.out.println("max::"+max.get().toString());
        Optional<Employee> min = employees.stream().min((x, y) -> Double.compare(x.getSalary(), y.getSalary()));
        System.out.println("min::"+min.get().toString());
    }

    /**
     * 报错 : java.lang.IllegalStateException: stream has already been operated upon or closed
     * 流进行了终止操作后,不能再次使用
     */
    @Test
    public void  test11(){
        Stream<Employee> stream = employees.stream();
        System.out.println(stream.count());
        stream.skip(2);
        System.out.println(stream.count());
    }
}

-----------------------------------------------------------------------------------------------------------------------------

package com.example.java8.java8test;

import java.util.Arrays;
import java.util.DoubleSummaryStatistics;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import com.example.java8.mapper.Employee;
import org.junit.Test;


public class StreamTest2 {

   /**
    * 当前公司的员工信息
    */
   private  List<Employee> employees = Arrays.asList(
         new Employee(1,"sun",25,5000.0, Employee.Status.BUSY),
         new Employee(3,"tina",22,4500.0, Employee.Status.FREE),
         new Employee(4,"jack",66,9900.0, Employee.Status.VOCATION),
         new Employee(5,"peter",77,4509.99, Employee.Status.BUSY),
         new Employee(6,"lose",10,888.8, Employee.Status.BUSY),
         new Employee(11,"lose",10,888.8, Employee.Status.BUSY),
         new Employee(12,"lose",10,888.8, Employee.Status.BUSY),
         new Employee(13,"lose",10,888.8, Employee.Status.BUSY),
         new Employee(7,"rise",39,682.2, Employee.Status.VOCATION),
         new Employee(8,"dex",56,15000.0, Employee.Status.VOCATION),
         new Employee(9,"great",12,3000.98, Employee.Status.FREE),
         new Employee(10,"lady",33,26859.2, Employee.Status.FREE)
   );
   
    /**
    * 归约
    * reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。
    */
   @Test
   public void test1(){
      List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
      Integer sum = list.stream()
         .reduce(0, (x, y) -> x + y);
      System.out.println(sum);
      System.out.println("<<<<<<<<<>>>>>>>>>>>");
      Optional<Double> op = employees.stream()
         .map(Employee::getSalary)
         .reduce(Double::sum);
      System.out.println(op.get());
   }

   /**
    * 例子
    * 搜索名字中 “e” 出现的次数
    */
   @Test
   public void test2(){
      Optional<Integer> sum = employees.stream()
         .map(Employee::getName)
         .flatMap(StreamTest::filterCharacter)
         .map((ch) -> {
            if(ch.equals('e'))
               return 1;
            else 
               return 0;
         }).reduce(Integer::sum);
      System.out.println(sum.get());
   }

   /**
    * collect——将流转换为其他形式。接收一个 Collector接口的实现,
    * 用于给Stream中元素做汇总的方法
    */
   @Test
   public void test3(){
      List<String> list = employees.stream()
         .map(Employee::getName)
         .collect(Collectors.toList());
      list.forEach(System.out::println);
      System.out.println("<<<<<<<<<>>>>>>>>>>>");
      Set<String> set = employees.stream()
         .map(Employee::getName)
         .collect(Collectors.toSet());
      set.forEach(System.out::println);
      System.out.println("<<<<<<<<<>>>>>>>>>>>");
      HashSet<String> hs = employees.stream()
         .map(Employee::getName)
         .collect(Collectors.toCollection(HashSet::new));
      hs.forEach(System.out::println);
   }
   
   @Test
   public void test4(){
      Optional<Double> max = employees.stream()
         .map(Employee::getSalary)
         .collect(Collectors.maxBy(Double::compare));
      System.out.println(max.get());
      Optional<Employee> op = employees.stream()
         .collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
      System.out.println(op.get());
      Double sum = employees.stream()
         .collect(Collectors.summingDouble(Employee::getSalary));
      System.out.println(sum);
      Double avg = employees.stream()
         .collect(Collectors.averagingDouble(Employee::getSalary));
      System.out.println(avg);
      Long count = employees.stream()
         .collect(Collectors.counting());
      System.out.println(count);
      System.out.println("<<<<<<<<<>>>>>>>>>>>");

      DoubleSummaryStatistics dss = employees.stream()
         .collect(Collectors.summarizingDouble(Employee::getSalary));
      System.out.println("Max::"+dss.getMax());
      System.out.println("Average::"+dss.getAverage());
      System.out.println("Count::"+dss.getCount());
      System.out.println("Min::"+dss.getMin());
      System.out.println("Sum::"+dss.getSum());
   }

   /**
    * Collectors
    * 分组
    */
   @Test
   public void test5(){
      Map<Employee.Status, List<Employee>> map = employees.stream()
         .collect(Collectors.groupingBy(Employee::getStatus));
      System.out.println(map);
   }

   /**
    * Collectors
    * 多级分组
    */
   @Test
   public void test6(){
      Map<Employee.Status, Map<String, List<Employee>>> map = employees.stream()
         .collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
            if(e.getAge() >= 60)
               return "老年";
            else if(e.getAge() >= 35)
               return "中年";
            else
               return "少年";
         })));
      System.out.println(map);
   }

   /**
    * Collectors
    * 分区
    */
   @Test
   public void test7(){
      Map<Boolean, List<Employee>> map = employees.stream()
         .collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));
      System.out.println(map);
   }

   @Test
   public void test8(){
      String str = employees.stream()
         .map(Employee::getName)
         .collect(Collectors.joining("," , "<<<<<", ">>>>>"));
      System.out.println(str);
   }
   
   @Test
   public void test9(){
      Optional<Double> sum = employees.stream()
         .map(Employee::getSalary)
         .collect(Collectors.reducing(Double::sum));
      System.out.println(sum.get());
   }
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值