JAVA8流操作

Wesley13
• 阅读 630
 * Stream 的三个操作步骤: * 1创建Stream * 2中间操作 * 3终止操作

package airycode_java8.nice6;

import airycode_java8.nice1.Employee;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * Stream 的三个操作步骤:
 * 1创建Stream
 * 2中间操作
 * 3终止操作
 * Created by admin on 2019/1/3.
 */
public class TestStream {

    @Test
    public void test1(){
        //1.通过Collection集合提供的stream()或者parallelStream()
        List<String> list = new ArrayList<>();
        Stream<String> stream1 = list.stream();
        //2.数组
        Employee[]emps = new Employee[10];
        Stream<Employee> stream2 = Arrays.stream(emps);
        //3.stream中的静态方法
        Stream.of("aa","bb","cc");

        //4.创建无限流
        //迭代
        Stream<Integer> stream = Stream.iterate(0, (x) -> x + 2);
        stream.limit(10).forEach(System.out::println);

        //生成
        Stream.generate(()->Math.random()).limit(5).forEach(System.out::println);

    }

}

  中间操作:

package airycode_java8.nice6;

import airycode_java8.nice1.Employee;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * 中间操作
 *
 * Created by admin on 2019/1/3.
 */
public class TestStreamApi2 {

    //准备数据
    static List<Employee> employeeList = Arrays.asList(
            new Employee("张三",18,9999.99, Employee.Status.FREE),
            new Employee("李四",38,5555.55,Employee.Status.BUSY),
            new Employee("王五",50,6666.66,Employee.Status.VOCATION),
            new Employee("赵六",16,3333.33,Employee.Status.FREE),
            new Employee("田七",8,7777.77,Employee.Status.BUSY)
    );
    /***
     * 筛选与切片
     * filter--接收Lambda,从流中排除某些元素。
     * limit--截断流,使其元素不超过给定数量
     * skip(n)--跳过元素,返回扔掉了前n个元素的流,若流中不足n个,则返回一个空流,与limit互补
     * distinct--筛选,通过流所生成的元素的hashcode和equals去除重复元素
     */
    //内部迭代:由StreamAPI提供
    @Test
    public void test1(){
        //中间操作:不会做任何的操作
        Stream<Employee> stream1 = employeeList.stream().filter((e) -> e.getAge() > 35);
        //终止操作:一次性执行全部,就是“惰性求值”
        stream1.forEach(System.out::println);
    }

    @Test
    public void test2(){
        //中间操作:不会做任何的操作
        Stream<Employee> stream1 = employeeList.stream().filter((e) -> e.getAge() > 35).limit(1);
        //终止操作:一次性执行全部,就是“惰性求值”
        stream1.forEach(System.out::println);
    }

    @Test
    public void test3(){
        //中间操作:不会做任何的操作
        Stream<Employee> stream1 = employeeList.stream().filter((e) -> e.getAge() > 35).skip(1);
        //终止操作:一次性执行全部,就是“惰性求值”
        stream1.forEach(System.out::println);
    }

    //去重必须重写hashcode和equals
    @Test
    public void test4(){
        //中间操作:不会做任何的操作
        Stream<Employee> stream1 = employeeList.stream().filter((e) ->e.getSalary()>5000).skip(2).distinct();
        //终止操作:一次性执行全部,就是“惰性求值”
        stream1.forEach(System.out::println);
    }
}

  中间操作2:

package airycode_java8.nice6;

import airycode_java8.nice1.Employee;
import org.junit.Test;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * 中间操作
 *
 * Created by admin on 2019/1/3.
 */
public class TestStreamApi3 {

    //准备数据
    static List<Employee> employeeList = Arrays.asList(
            new Employee("张三",18,9999.99, Employee.Status.FREE),
            new Employee("李四",38,5555.55,Employee.Status.BUSY),
            new Employee("王五",50,6666.66,Employee.Status.VOCATION),
            new Employee("赵六",16,3333.33,Employee.Status.FREE),
            new Employee("田七",8,7777.77,Employee.Status.BUSY)
    );
    /***
     * 映射
     * map--接收Lambda,将元素转换成其他形式或提取信息,接收一个函数作为参数,该函数会被应用到每一个元素上,并将其映射成一个新的元素
     * flatMap--接收一个函数作为参数,将流中的,每一个值换成另一个流,然后把所有流链接成一个流
     */
    //内部迭代:由StreamAPI提供
    @Test
    public void test1(){
        List<String> list = Arrays.asList("aaa","bbb","ccc","ddd");
        list.stream().map((str)->str.toUpperCase()).forEach(System.out::println);
        System.out.println("------------------------");
        employeeList.stream().map((employee -> employee.getName())).forEach(System.out::println);
    }

    //map对比flatMap
    @Test
    public void test2(){
        List<String> list = Arrays.asList("aaa","bbb","ccc","ddd");
        Stream<Stream<Character>> charStream = list.stream().map(TestStreamApi3::filterChar);
        charStream.forEach((sm)->{
            sm.forEach(System.out::println);
        });


    }

    //flatMap
    @Test
    public void test3(){
        List<String> list = Arrays.asList("aaa","bbb","ccc","ddd");
        list.stream().flatMap(TestStreamApi3::filterChar).forEach(System.out::println);


    }

    public static Stream<Character> filterChar(String str){
        List<Character> list = new ArrayList<>();
        for (Character c:str.toCharArray()) {
            list.add(c);
        }

        return list.stream();
    }

}

  中间操作-排序

package airycode_java8.nice6;

import airycode_java8.nice1.Employee;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * 中间操作--排序
 *
 * Created by admin on 2019/1/3.
 */
public class TestStreamApi4 {

    //准备数据
    static List<Employee> employeeList = Arrays.asList(
            new Employee("张三",18,9999.99, Employee.Status.FREE),
            new Employee("李四",38,5555.55,Employee.Status.BUSY),
            new Employee("王五",50,6666.66,Employee.Status.VOCATION),
            new Employee("赵六",16,3333.33,Employee.Status.FREE),
            new Employee("田七",8,7777.77,Employee.Status.BUSY)
    );
    /***
     * 排序
     * sorted()-自然排序
     * sorted(Comparator com)--定制排序
     */
    @Test
    public void test1(){
        List<String> list = Arrays.asList("fff","aaa","bbb","ccc","ddd");
        list.stream().sorted().forEach(System.out::println);
        System.out.println("---------------------");
        employeeList.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);
    }



}

  终止操作:

package airycode_java8.nice6;

import airycode_java8.nice1.Employee;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 终止操作
 *
 * Created by admin on 2019/1/3.
 */
public class TestStreamApi5 {

    //准备数据
    static List<Employee> employeeList = Arrays.asList(
            new Employee("张三",18,9999.99, Employee.Status.FREE),
            new Employee("李四",38,5555.55,Employee.Status.BUSY),
            new Employee("王五",50,6666.66,Employee.Status.VOCATION),
            new Employee("赵六",16,3333.33,Employee.Status.FREE),
            new Employee("田七",8,7777.77,Employee.Status.BUSY)

    );
    /***
     * 终止操作
     * 查找与匹配
     * allMatch--检查是否匹配所有元素
     * anyMatch--检查是否至少匹配一个元素
     * noneMatch--检查是否没有匹配所有元素
     * findFirst--返回第一个元素
     * findAny--返回当前流中的任意一个元素
     * count--返回流中元素总个数
     * max--返回流中最大值
     * min--返回流中最小值
     *
     *
     */
    @Test
    public void test1(){
        boolean allMatch = employeeList.stream().allMatch((employee -> employee.getStatus().equals(Employee.Status.BUSY)));
        System.out.println(allMatch);

        boolean anyMatch = employeeList.stream().anyMatch((employee -> employee.getStatus().equals(Employee.Status.BUSY)));
        System.out.println(anyMatch);

        boolean noneMatch = employeeList.stream().noneMatch((employee -> employee.getStatus().equals(Employee.Status.BUSY)));
        System.out.println(noneMatch);

        Optional<Employee> op = employeeList.stream().sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())).findFirst();
        Employee employee = op.get();
        System.out.println(employee);

        System.out.println("-------------------------");
        Optional<Employee> anyOp = employeeList.stream().filter((e) -> e.getStatus().equals(Employee.Status.FREE)).findAny();
        System.out.println(anyOp.get());
    }

    @Test
    public void test2(){
        long count = employeeList.stream().count();
        System.out.println(count);
        Optional<Employee> max = employeeList.stream().max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
        System.out.println(max.get());
        Optional<Employee> min = employeeList.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
        System.out.println(min.get());

        Optional<Double> min1 = employeeList.stream().map(Employee::getSalary).min(Double::compare);
        System.out.println(min1.get());
    }



}

  终止操作:规约

package airycode_java8.nice6;

import airycode_java8.nice1.Employee;
import org.junit.Test;

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

/**
 * 终止操作
 *
 * Created by admin on 2019/1/3.
 */
public class TestStreamApi6 {

    //准备数据
    static List<Employee> employeeList = Arrays.asList(
            new Employee("张三",18,9999.99, Employee.Status.FREE),
            new Employee("李四",38,5555.55,Employee.Status.BUSY),
            new Employee("王五",50,6666.66,Employee.Status.VOCATION),
            new Employee("赵六",16,3333.33,Employee.Status.FREE),
            new Employee("田七",8,7777.77,Employee.Status.BUSY)

    );
    /***
     * 规约
     * reduce(T identity,BinaryOperator)--可以将流中元素反复结合起来,得到一个值
     *
     *
     */
    @Test
    public void test1(){
        List<Integer> list = Arrays.asList(1,2,3,4,5);
        Integer sum = list.stream().reduce(0, (x, y) -> x + y);
        System.out.println(sum);
        System.out.println("-----------------------");
        Optional<Double> reduceOp = employeeList.stream().map(Employee::getSalary).reduce(Double::sum);
        System.out.println(reduceOp.get());
    }


    /***
     * 收集
     * collect--将流转化为其他的形式,接收一个Collector接口的实现,用于给Stream中元素做汇总的方法
     */


    @Test
    public void test2(){
        List<String> names = employeeList.stream().map(Employee::getName).collect(Collectors.toList());
        names.forEach(System.out::println);

        Set<String> disNames = employeeList.stream().map(Employee::getName).collect(Collectors.toSet());
        disNames.forEach(System.out::println);

        System.out.println("----------------");
        HashSet<String> hashNames = employeeList.stream().map(Employee::getName).collect(Collectors.toCollection(HashSet::new));
        hashNames.forEach(System.out::println);
    }


    @Test
    public void test3(){
        //总数
        Long count = employeeList.stream().collect(Collectors.counting());
        System.out.println(count);

        //平均数
        Double avg = employeeList.stream().collect(Collectors.averagingDouble(Employee::getSalary));
        System.out.println(avg);

        //总和
        Double sum = employeeList.stream().collect(Collectors.summingDouble(Employee::getSalary));
        System.out.println(sum);

        //最大值员工
        Optional<Employee> employeeMax = employeeList.stream().collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
        System.out.println(employeeMax.get());

        //最小值
        Optional<Double> val = employeeList.stream().map(Employee::getSalary).collect(Collectors.minBy(Double::compare));
        System.out.println(val.get());
    }


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

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

    //分区
    @Test
    public void test6(){
        Map<Boolean, List<Employee>> booleanListMap = employeeList.stream().collect(Collectors.partitioningBy((e) -> e.getSalary() > 8000));

        System.out.println(booleanListMap);
    }

    //获取最大值,求和,最小值,另一种方式
    @Test
    public void test7(){
        DoubleSummaryStatistics dss = employeeList.stream().collect(Collectors.summarizingDouble(Employee::getSalary));

        System.out.println(dss.getSum());
        System.out.println(dss.getAverage());
        System.out.println(dss.getCount());
        System.out.println(dss.getMax());
        System.out.println(dss.getMin());
    }

    //连接字符换
    @Test
    public void test8(){
        String str = employeeList.stream().map(Employee::getName).collect(Collectors.joining("-"));
        System.out.println(str);
    }





}
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
3年前
Python3:sqlalchemy对mysql数据库操作,非sql语句
Python3:sqlalchemy对mysql数据库操作,非sql语句python3authorlizmdatetime2018020110:00:00coding:utf8'''
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这