java8 Stream 使用案例

预定义示例参数

static class TestUser {
        private Integer id;
        private String name;
        private String mobile;

        public TestUser(){

        }

        public TestUser(String name, String mobile) {
            this.id = new Random().nextInt(Integer.MAX_VALUE);
            this.name = name;
            this.mobile = mobile;
        }

        public Integer getId() {
            return id;
        }

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

        public String getName() {
            return name;
        }

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

        public String getMobile() {
            return mobile;
        }

        public void setMobile(String mobile) {
            this.mobile = mobile;
        }

        @Override
        public String toString() {
            return "TestUser{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", mobile='" + mobile + '\'' +
                    '}';
        }
    }
List<TestUser> userList = Arrays.asList(
                new TestUser("字符串1","114"),
                new TestUser("字符串2","125"),
                new TestUser("字符串3","136"),
                new TestUser("a^z","147"),
                new TestUser("0~9","158"),
                new TestUser("A^Z","169")

        );
        List<String> list = Arrays.asList("字符串1","字符串22","字符串333","a^z","0~9","A^Z");

filter

	/**
     * filter : 条件过滤 类似于if,过滤后还是当前流
     * @param list
     */
    public static void streamFilter(List<String> list){
        System.out.println("**********************filter**************************");
        Stream<String> stringStream = list.stream().filter(c -> c.equals("字符串1"));
        stringStream.findFirst().ifPresent(System.out::println);
    }

map

	/**
     * 接收一个函数作为参数,此函数作用到Stream中每一个元素,形成一个新的元素,所有新的元素组成一个新的流。
     * map : 使用map过滤的内容,map 中 使用的是当前该对象通用的内容,可以转成map集合 通用类型(共性),或者转成数据流。
     * @param list
     */
    public static void streamMap(List<String> list){
        System.out.println("**********************map**************************");
        // 转为数据流
        Stream<Integer> integerStream = list.stream().map(String::length);
        // 转为list对象
        List<Integer> collectList = list.stream().map(String::length).collect(Collectors.toList());
        // 转为map 当前的示范为错误数据,map的唯一key不能重复,否则在赋值时会产生 Duplicate key
//        Map<Integer, String> collectMap = list.stream().map(String::length).collect(Collectors.toMap(c -> c.intValue(), k -> k.toString()));
        System.out.println("转为数据流输出");
        integerStream.findAny().ifPresent(System.out::println);
        System.out.println("转为list对象");
        collectList.forEach(System.out::println);
    }

mapToInt

	/**
     * mapToInt 使用当前方法是内置方法结果返回流数据必须是int类型,返回为 IntStream 类型,可再次作其他操作。
     * 强转类型一定要注意内容是否存在非强转类型
     * @param list 演示
     */
    public static void mapToInt(List<TestUser> list){
        System.out.println("**********************mapToInt 或 可向下强转 **************************");
        IntStream intStream = list.stream().mapToInt(c -> c.id);
        intStream.forEach(System.out::println);
    }

mapToLong

	/**
     * mapToLong 使用当前方法是内置方法结果返回流数据必须是Long 或 可向下强转 类型,返回为 LongStream 类型,可再次作其他操作。
     * 强转类型一定要注意内容是否存在非强转类型
     * @param list 演示
     */
    public static void mapToLong(List<TestUser> list){
        System.out.println("**********************mapToLong**************************");
        LongStream longStream = list.stream().mapToLong(c -> c.id);
        longStream.forEach(System.out::println);
    }

mapToDouble

	/**
     * mapToDouble 使用当前方法是内置方法结果返回流数据必须是Double 或 可向下强转 类型,返回为 DoubleStream 类型,可再次作其他操作。
     * 强转类型一定要注意内容是否存在非强转类型
     * @param list 演示
     */
    public static void mapToDouble(List<TestUser> list){
        System.out.println("**********************mapToDouble**************************");
        DoubleStream stream = list.stream().mapToDouble(c -> c.id);
        stream.forEach(System.out::println);
    }

peek

	/**
     * 中间操作 对数据进行加工或者展示,操作的流对象没有更换。
     * 当前方法 peek 就是中间操作。(终止操作:即将当前流数据转换为其他类型数据,对流的当前操作已经结束,可以进行下一次的流操作)
     * @param list
     */
    public static void peek(List<TestUser> list){
        System.out.println("**********************peek**************************");
        list.stream().peek(c -> {
            // 可以对内附对象最初修正操作或者其他业务操作
            System.out.println(c);
        }).collect(Collectors.toList());
    }

flatMap

	/**
     * 接收一个函数作为参数,它将流中的每个元素都转换成另一个流,然后把所有流再连接形成一个最终流。
     * @param list
     */
    public static void flatMap(List<TestUser> list){
        System.out.println("**********************flatMap**************************");
        List<List<TestUser>> flatList = Arrays.asList(list);
        flatList.stream().flatMap(c -> c.stream().distinct()).collect(Collectors.toList()).forEach(c -> System.out.println(c));
    }

flatMapToInt

	/**
     * 操作的流数据必须返回的是int类型的流内容
     * flatMapToLong
     * flatMapToDouble
     * 以上同理
     * @param list
     */
    public static void flatMapToInt(List<TestUser> list){
        System.out.println("**********************flatMapToInt**************************");
        List<List<TestUser>> flatList = Arrays.asList(list);
        flatList.stream().flatMapToInt(c -> c.stream().map(TestUser::getId).mapToInt(Integer::intValue)).forEach(System.out::println);
    }

distinct

	/**
     * 去重
     * @param list
     */
    public static void distinct(List<TestUser> list){
        System.out.println("**********************distinct**************************");
        Set<Integer> collect = list.stream().peek(c -> {
             System.out.println("原:" + c.id);
             c.id = Optional.of(c.id).filter(x -> x > 0 && x % 2 == 0).orElse(123);
        }).map(TestUser::getId).collect(Collectors.toSet());
        collect.forEach(System.out::println);
        // 或者
        list.stream().peek(c -> {
            System.out.println("原:" + c.id);
            c.id = Optional.of(c.id).filter(x -> x > 0 && x % 2 == 0).orElse(123);
        }).map(TestUser::getId).distinct().collect(Collectors.toList()).forEach(System.out::println);
    }

sorted

	/**
     * 排序
     * @param list
     */
    public static void sorted(List<TestUser> list){
        System.out.println("**********************sorted**************************");
        System.out.println("升序:");
        list.stream().sorted(Comparator.comparing(TestUser::getId)).collect(Collectors.toList()).forEach(System.out::println);
        System.out.println("降序:");
        list.stream().sorted(Comparator.comparing(TestUser::getId).reversed()).collect(Collectors.toList()).forEach(System.out::println);
    }

limit

	/**
     * 限制流内容的数量
     * limit/skip 也不是终止操作,中间操作,操作完成的对象还是当前流本身,只是对数据内容做了处理。
     *
     * @param list
     */
    public static void limit(List<TestUser> list){
        System.out.println("**********************limit**************************");
        // 截取第一个
        list.stream().limit(1).forEach(System.out::println);
        // 跳过第一个截取两个
	    list.stream().skip(1).limit(2).forEach(System.out::println);
    }

forEach

	 /**
     * 循环
     * @param list
     */
    public static void forEach(List<TestUser> list){
        System.out.println("**********************forEach**************************");
        list.stream().forEach(System.out::println);
    }

forEachOrdered

	/**
     * 强制排序 无论是串行流还是并行流使用当前方法都要进行排序
     * @param list
     */
    public static void forEachOrdered(List<TestUser> list){
        System.out.println("**********************forEachOrdered**************************");
        list.stream().forEach(System.out::println);
        System.out.println("---");
        list.stream().forEachOrdered(System.out::println);
        System.out.println("---");
        list.parallelStream().forEach(System.out::println);
        System.out.println("---");
        list.parallelStream().forEachOrdered(System.out::println);
    }

reduce

	/**
     * 可用于计算,将多个值通过制定业务计算规则为一个值
     * @param list
     */
    public static void reduce(List<TestUser> list){
        System.out.println("**********************reduce**************************");
        List<Integer> arrList = Arrays.asList(1,23,40,60,70,34,35);
        // 求和
        list.stream().mapToInt(c -> c.id = new Random().nextInt(1000)).reduce(Integer::sum).ifPresent(System.out::println);
        // 求最大值
        list.stream().mapToInt(c -> c.id = new Random().nextInt(1000)).reduce(Integer::max).ifPresent(System.out::println);
        // 基于一个变量值 与 1001比较 大于展示自身 小于展示1001
        System.out.println(list.stream().mapToInt(c -> c.id = new Random().nextInt(1000)).reduce(1001, Integer::max));
        // 基于一个变量值 累加
        System.out.println(list.stream().mapToInt(c -> c.id = new Random().nextInt(1000)).reduce(1001, Integer::sum));
        // 求最大值
        arrList.stream().reduce((x,y) -> x > y ? x : y).ifPresent(System.out::println);
        arrList.stream().reduce(Integer::max).ifPresent(System.out::println);
        // 最小值
        arrList.stream().reduce(Integer::min).ifPresent(System.out::println);
        // 集合乘积
        arrList.stream().reduce((x,y) -> x * y).ifPresent(System.out::println);
    }

minAMax

	/**
     * 最大、最小 、求和
     * @param list
     */
    public static void minAMax(List<TestUser> list){
        System.out.println("**********************min&Max**************************");
        List<Integer> arrList = Arrays.asList(1,23,40,60,70,34,35);
        arrList.stream().min(Integer::compareTo).ifPresent(System.out::println);
        arrList.stream().max(Integer::compareTo).ifPresent(System.out::println);
        System.out.println(arrList.stream().mapToInt(c -> c.intValue()).sum());
    }

count

	/**
     * count  计数
     * @param list
     */
    public static void count(List<TestUser> list){
        System.out.println("**********************count**************************");
        List<Integer> arrList = Arrays.asList(1,23,40,60,70,34,35);
        System.out.println(arrList.stream().count());
    }

match

	/**
     * anyMatch  只要有一个匹配 true
     * allMatch  必须所有都匹配 true
     * noneMatch 不能又一个匹配 true
     * @param list
     */
    public static void match(List<TestUser> list){
        System.out.println("**********************xx**************************");
        List<Integer> arrList = Arrays.asList(1,23,40,60,70,34,35);
        System.out.println(arrList.stream().anyMatch(c -> c > 2));
        System.out.println(arrList.stream().allMatch(c -> c > 2));
        System.out.println(arrList.stream().noneMatch(c -> c > 2));
    }

stream静态

	/**
     * stream 静态方法
     */
    public static void stream(){
        System.out.println("**********************Stream**************************");
        Stream<Object> empty = Stream.empty();
        Stream<Object> build = Stream.builder().build();
        Stream<Integer> integerStream1 = Stream.of(1, 2, 3, 4, 6);
        Stream<Integer> integerStream2 = Stream.of(1, 2, 3, 4, 6);
        Stream<String> stringStream = Stream.of("1", "2", "3", "4");
        // 根据规则生成一些内容 输出10 个奇数
        Stream.iterate(1, c -> c + 2).limit(10).forEach(System.out::println);
        Stream<UUID> limit = Stream.generate(UUID::randomUUID).limit(2);
        Stream<TestUser> generate = Stream.generate(TestUser::new).limit(3);
        System.out.println("-------------");
        // 不去重 合并相同规则内容
        Stream.concat(integerStream1, integerStream2).distinct().forEach(System.out::println);
    }

加油!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值