Stream API

01、准备

为了学习方便创建的实体类

//实体类
public class Employee {
    private Integer age;
    private String name;
    private Status status;
}
//状态枚举类
public enum Status{
    LIZHI,
    BUSY,
    VOCATION
}

02、创建流

  1. collection系列集合提供的stream()方法 或paralleStream
  2. 通过Arrays 中的静态方法stream()
  3. Stream中的静态方法of()
        //1、collection系列集合提供的stream()方法 或paralleStream
        Stream<Employee> stream = emps.stream();
        //2、通过Arrays 中的静态方法stream()
        Employee[] emps1 = new Employee[10];
        Stream<Employee> stream1 = Arrays.stream(emps1);
        //3、Stream中的静态方法of()
        Stream<String> stream2 = Stream.of("a", "b", "c");

03、操作流

1、筛选与切片

  • filter:接收lamda,从流中排除一些元素
  • limit:截断取出指定数量
  • skip(n):跳过元素,返回一个扔掉前n个元素的流,若流中元素不足n则返回一个空流
  • distinct:筛选,通过流所生成的元素的hashcode 和equals方法去除再重复元素
        List<Employee> emps = Arrays.asList(
                new Employee(27,"刘富强"),
                new Employee(34,"刘民主"),
                new Employee(23,"刘文明"),
                new Employee(42,"刘和谐"),
                new Employee(19,"刘自由"),
                new Employee(24,"刘平等"),
                new Employee(32,"刘公平"),
                new Employee(28,"刘法治"),
                new Employee(33,"刘爱国"),
                new Employee(37,"刘敬业")

        );

		//1、filter 筛选30岁以上的员工
        stream.filter(x  -> x.getAge() > 30).forEach(System.out::println);
        //打印结果:
        Employee(age=34, name=刘民主, status=null)
		Employee(age=42, name=刘和谐, status=null)
		Employee(age=32, name=刘公平, status=null)
		Employee(age=33, name=刘爱国, status=null)
		Employee(age=37, name=刘敬业, status=null)
<======================================================>
        //2、filter 筛选30岁以上的员工 取出前三个
        stream.filter(x  -> x.getAge() > 30).limit(3).forEach(System.out::println);
        //打印结果:
        Employee(age=34, name=刘民主, status=null)
		Employee(age=42, name=刘和谐, status=null)
		Employee(age=32, name=刘公平, status=null)
<=====================================================>
		 //3、filter 筛选30岁以上的员工 跳过前四个
        stream.filter(x  -> x.getAge() > 30).skip(4).forEach(System.out::println);
        //打印结果:
		Employee(age=37, name=刘敬业, status=null)

distinct是去重操作,于是我将Employee(37,“刘敬业”)多添加了三条记录

        List<Employee> emps = Arrays.asList(
                new Employee(32,"刘公平"),
                new Employee(28,"刘法治"),
                new Employee(33,"刘爱国"),
                new Employee(37,"刘敬业"),
                new Employee(37,"刘敬业"),
                new Employee(37,"刘敬业")

        );
		stream.filter(x  -> x.getAge() > 30).distinct().forEach(System.out::println);
		//打印结果:去除了重复的记录
		Employee(age=32, name=刘公平, status=null)
		Employee(age=33, name=刘爱国, status=null)
		Employee(age=37, name=刘敬业, status=null)

2、映射

  • map(Function f) :接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
  • flatMap(Function f) :接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有的流连接成一个流
	List<String> emps = Arrays.asList("aa","bb","cc","dd","ee","ff");
	Stream<String> stream = emps.stream();
	
	//将字符转换成待大写
	stream.map(String::toUpperCase).forEach(System.out::println);
	//打印结果:
	AA
	BB
	CC
	DD
	EE
	FF

现在有这样的一种情况,此时stream1是一个包含着Stream流的一个流,,此时steam1类似{{a,a},{b,b},{c,c},{d,d},{e,e},{f,f}}。但是使用flatMap就类似于{a,a,b,b,c,c,d,d,e,e,f,f}

	List<String> emps = Arrays.asList("aa","bb","cc","dd","ee","ff");
    Stream<String> stream = emps.stream();
    //steam流经过映射后返回steam1
	Stream<Stream<Character>> stream1 = stream.map((x) -> filterCharacter(x));
	//打印stream1:是这样样式
	java.util.stream.ReferencePipeline$Head@15f8701f
	java.util.stream.ReferencePipeline$Head@514cd540
	......
<=========================================================>
Stream<Character> characterStream = stream.flatMap(x -> filterCharacter(x));


    //返回一个stream<Character>
    public Stream<Character> filterCharacter(String str){
        List<Character> list = new ArrayList<>();
        for (char c : str.toCharArray()) {
            list.add(c);
        }
        return list.stream();
    }

3、排序

  • sorted():自然排序
  • sorted(Comparator com):定制排序
	//自然排序
    List<String> list = Arrays.asList("bb","aa","ee","jj","cc","dd");
    Stream<String> stream = list.stream();
    stream.sorted().forEach(System.out::println);
    //打印结果:
    aa bb cc dd ee jj

对employee进行定制排序

        List<Employee> emps = Arrays.asList(
                new Employee(27,"刘富贵"),
                new Employee(34,"刘生产"),
                new Employee(23,"刘团结"),
                new Employee(23,"刘向前"),
                new Employee(19,"刘复兴")

        );
        Stream<Employee> stream1 = emps.stream();
        stream1.sorted((x,y) -> {
            if(x.getAge().equals(y.getAge())){
                return x.getName().compareTo(y.getName());
            }
            return Integer.compare(x.getAge(),y.getAge());
        }).forEach(System.out::println);

4、查找与匹配

  • allMatch :检查是否匹配所有元素,不全部匹配返回false
  • anyMatch :检查是否至少匹配一个元素
  • noneMatch :检查是否没有匹配所有元素
  • findFirst :返回第一个元素
  • findAny :返回当前流中的任意元素
  • count :返回流中的元素总个数
  • max :返回流中的最大值
  • min :返回流中的最小值
        List<Employee> emps = Arrays.asList(
                new Employee(27,"刘富贵", Status.ZAIZHI),
                new Employee(34,"刘生产",Status.BUSY),
                new Employee(23,"刘团结",Status.LIZHI),
                new Employee(23,"刘向前",Status.VOCATION),
                new Employee(19,"刘复兴",Status.ZAIZHI)

        );
        Stream<Employee> stream = emps.stream();
        boolean b = stream.allMatch(x -> x.getStatus().equals(Status.LIZHI));
        System.out.println(b); //false

        boolean c = stream.anyMatch(x -> x.getStatus().equals(Status.LIZHI));
        System.out.println(c);//true

        boolean b = stream.noneMatch(x -> x.getStatus().equals(Status.LIZHI));
        System.out.println(b);//false

        Optional<Employee> first = stream.findFirst();
        System.out.println(first);

        Optional<Employee> max = stream.max((x, y) -> x.getAge().compareTo(y.getAge()));
        System.out.println(max);

5、归约,转换

  • reduce:将流中的元素结合起来,得到一个值
  • collect:收集将流转换为其他的形式,接受一个collector的接口的实现,用于Stream中做元素汇总的方法

reduce使用有两种形式,一种存在起始值,返回Interger类型,第二种无起始值,返回Optional类型

        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        Stream<Integer> stream = list.stream();
        
        Integer reduce = stream.reduce(0, (x, y) -> x + y);
        
        Optional<Integer> reduce1 = stream.reduce((x, y) -> x + y);

在collect()中传入Collector接口的实现,这个实现类可以使用Collectors提供的静态方法得到。

        List<Employee> emps = Arrays.asList(
                new Employee(27,"刘富贵", Status.ZAIZHI),
                new Employee(34,"刘生产",Status.BUSY),
                new Employee(23,"刘团结",Status.LIZHI),
                new Employee(23,"刘向前",Status.VOCATION),
                new Employee(19,"刘复兴",Status.ZAIZHI)

        );
        
        Stream<Employee> stream = emps.stream();
        List<String> nameList = stream.map(x -> x.getName()).collect(Collectors.toList());
        System.out.println(nameList);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值