java8—streamAPI(四)

<streamApI(一)>

   1.中间操作

   2.筛选与切片

      filter -- 接收lambda,从流中排除某些元素。

      limit(n) -- 截断流,使其元素不超过给定数量。

      skip(n) -- 跳过元素,返回一个扔掉了前n个元素,不足n个元素,则返回一个空流。与limit 互补。

      distinct -- 筛选,通过流所生成的元素的hashCode() 和 equals()去除重复元素。

    3.映射

       map -- -接收lambda,将元素转换其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新元素。

    4.排序

       sorted() -- 自然排序

       sorted(Comparator c) -- 定制排序

提供一个Employee类

@Getter
@setter
public class Employee{  
   private String name;  
   private int age;  
   private double salary;  
   public Employee(){}  
   public Employee(String name,int age,double salary){  
   this.name = name;  
   this.age = age;  
   this.salary = salary;   
   }  
} 

初始化员工信息,注:后续所有test方法都在TestStreamAPI 类中

public class TestStreamAPI{
  //初始化员工信息  
   List<Employee> emps = Arrays.asList(new Employee("Kiven",24,10000),new Employee("Nick",40,39999),new Employee("Lily",25,8000)); 
}

①中间操作,终止操作

public void test1(){
 Stream<Employee> s = emps.stream.filter(
   e -> {
    Sysem.out.prinln("中间操作"); //不会执行任何操作
    return e.getAge()>35;
  });
   s.forEach(System.out::println); //终止操作:一次性执行全部内容,“惰性求值”
}

②limit截断流

public void test2(){
     emps.stream().filter((e) -> e.getSalary() > 5000).limit(4).forEach(System.out::println);
}

③skip跳过元素

public void test3(){
     emps.stream().filter((e) -> e.getSalary() > 5000).skip(2).forEach(System.out::println);
}

④distinct去重

public void test4(){
        employees.stream().filter((e) -> e.getSalary() > 5000).distinct().forEach(System.out::println);
}

④map映射

public void test5(){
   List<String> list = Arrays.asList("aa","bb");
   list.stream().map(String::toUpperCase).forEach(System.out::println);
}

⑤排序

 

public void test6(){
  List<String> list = Arrays.asList("aaa", "bbb", "ddd", "ccc", "eee");
        list.stream().sorted().forEach(System.out::println); //自然排序
        System.out.println("-----------------------");
        employees.stream().sorted((e1, e2) -> {      //定制排序
            if (e1.getAge() == (e2.getAge())) {
                return e1.getName().compareTo(e2.getName());
            } else {
                return Integer.compare(e1.getAge(), (e2.getAge()));
            }
        }).forEach(System.out::println);
}

<streamApi(二)>

    1.查找与匹配

        allMathch   --检查是否匹配所有元素
        anyMatch   --检查是否至少匹配一个元素
        noneMatch --检查是否没有匹配所有元素
        findFirst      --返回第一个元素
        findAny       --返回当前流中任意一个元素
        count           --返回流中的匹配到元素的个数
        max             --返回流中最大值

        min              --返回流中最小值

   2.规约

         reduce -- 将流中元素反复结合起来得到一个元素,通常和map搭配使用

  3.收集

       collect(Collectors.method()) --将流中元素反复结合起来得到一个元素

①allMatch , anyMatch , noneMatch

public void test1(){
   boolean b1 = employees.stream().allMatch(e -> e.getName().equals("Ryan"));
        System.out.println("b1: " + b1);
        boolean b2 = employees.stream().anyMatch(e -> e.getName().equals("Ryan"));
        System.out.println("b2: " + b2);
        boolean b3 = employees.stream().noneMatch(e -> e.getName().equals("Kiven"));
        System.out.println("b3: " + b3);
}

②findFirst,findAny

public void test2(){
        //先对雇员信息从大到小排序,再取出第一条记录
        Optional<Employee> employee = employees.stream().sorted((e1, e2) -> Double.compare(e2.getSalary(), e1.getSalary())).findFirst();
        System.out.println(employee.get());

        Employee ep = employees.stream().sorted((e1, e2) -> Double.compare(e2.getSalary(), e1.getSalary())).findFirst().orElse(null);
        System.out.println(ep);

        Optional<Employee> employee1 = employees.stream().filter(e -> e.getName().equals("Ryan")).findAny();
        Optional<Employee> employee2 = employees.parallelStream().filter(e -> e.getName().equals("Ryan")).findAny();

        System.out.println(employee1.get());
        System.out.println(employee2.get());
}

③count,max ,min

public void test3(){
    long count = employees.stream().count();
        System.out.println("count: " + count);

        //如果有找到两个,则返回第一个
        Optional<Employee> optional = employees.stream().max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
        System.out.println("optional: " + optional);

        Optional<Double> option = employees.stream().map(Employee::getSalary).min(Double::compare);
        System.out.println("option: " + option.get());

        Optional<Employee> optional2 = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
        System.out.println("optional2: " + optional2.get());
}

④reduce

public void test4(){
    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());
}

⑤collect

 

public void test5(){
        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);

        long count = employees.stream().collect(Collectors.counting());
        System.out.println(count);

        Double avg = employees.stream().collect(Collectors.averagingDouble(Employee::getSalary));
        System.out.println(avg);

        Double sum = employees.stream().collect(Collectors.summingDouble(Employee::getSalary));
        System.out.println(sum);
}

⑥拓展:分组,多级分组

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

        //多级分组
        Map<Employee.Status, Map<String, List<Employee>>> map1 = employees.stream().collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy(e -> {
            if (e.getAge() <= 35) {
                return "青年";
            } else if (e.getAge() <= 50) {
                return "中年";
            } else {
                return "老年";
            }
        })));
        System.out.println(map1);

        //分区
        Map<Boolean, List<Employee>> map2 = employees.stream().collect(Collectors.partitioningBy(e -> e.getSalary() > 8000));
        System.out.println(map2);

        DoubleSummaryStatistics dss = employees.stream().collect(Collectors.summarizingDouble(Employee::getSalary));
        System.out.println(dss.getSum());
        System.out.println(dss.getAverage());
        System.out.println(dss.getMax());

        String str = employees.stream().map(Employee::getName).collect(Collectors.joining(",", "/", "-"));

        System.out.println(str);
    }

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值