浅聊一下Stream流

目录

通过stream获取集合中指定数据:

获取流:

stream流中的foreach方法:

stream流中的filter方法:

stream流中的limit方法:

stream流中的skip方法:

 Stream流中的map方法:

stream流中的sorted方法:

Stream流中的distinct方法:

Stream流的match方法:

Stream流的find方法:

Stream流中的max和min方法:

 Stream流的reduce方法:

Stream的concat方法:

Stream小练习:

将流中的数据收集到集合中:

将流中的数据收集到数组中:

对流中数据进行聚合运算:

对流中数据进行分组:

 多级分组:

对流中数据进行拼接:

Optional类的基本使用:


参考:https://www.bilibili.com/video/BV1zJ411R7uQ/?vd_source=c75e68fd099206ad9761f2134ce79ce2

推荐博客:恕我直言,我怀疑你没怎么用过Stream流

我的是直接实战演示,大家想要知道概念什么的话可以参考一下上面的博客。

下面的内容写的可能比较混乱

通过stream获取集合中指定数据:

package com.jdktest01.day02;

import java.util.ArrayList;
import java.util.Collections;

/**
 * @author a1002
 */
public class StreamTest01 {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        Collections.addAll(list, "张无忌", "周芷若", "赵敏", "张三丰", "师太", "韦小宝", "康熙");

        ArrayList<String> zhangList = new ArrayList<>();
        list.stream()
                .filter((s) -> {
                    return s.startsWith("张");
                })
                .filter((s) -> {
                    return s.length() == 3;
                })
                //遍历
                .forEach((s) -> {
                    System.out.println(s);
                    System.out.println(s.length());
                    //添加到集合中
                    zhangList.add(s);
                });

        System.out.println("=========================");
        //拿到所有姓张的且长度为3的
        //集合遍历
        System.out.println(zhangList);
        System.out.println("---------------------------");
        list.forEach(System.out::println);
    }
}

获取流:

package com.jdktest01.day02;

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

/**
 * @author a1002
 */
public class StreamTest03 {
    public static void main(String[] args) {
        // 方式1 : 根据Collection获取流
        // Collection接口中有一个默认的方法: default Stream<E> stream()
        List<String> list = new ArrayList<>();
        Stream<String> stream1 = list.stream();

        Set<String> set = new HashSet<>();
        Stream<String> stream2 = set.stream();

        Map<String, String> map = new HashMap<>();
        Stream<String> stream3 = map.keySet().stream();
        Stream<String> stream4 = map.values().stream();
        Stream<Map.Entry<String, String>> stream5 = map.entrySet().stream();

        // 方式2 : Stream中的静态方法of获取流
        // static<T> Stream<T> of(T... values)
        Stream<String> stream6 = Stream.of("aa", "bb", "cc");

        String[] strs = {"aa", "bb", "cc"};
        Stream<String> stream7 = Stream.of(strs);

        // 基本数据类型的数组行不行?不行的,会将整个数组看做一个元素进行操作.
        int[] arr = {11, 22, 33};
        Stream<int[]> stream8 = Stream.of(arr);
    }
}

stream流中的foreach方法:

package com.jdktest01.day02;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author a1002
 */
public class StreamTest04 {
    public static void main(String[] args) {
        List<String> one = new ArrayList<>();
        Collections.addAll(one, "迪丽热巴", "周雨彤", "马思纯", "肖战", "老子", "庄子");
        one.stream().forEach((String str) -> {
            System.out.println(str);
        });
        System.out.println("-------------------------");
        one.stream().forEach(System.out::println);
        System.out.println("-------------------------");
        one.forEach(System.out::println);
    }
}

stream流中的filter方法:

//过滤

List<String> one = new ArrayList<>();
        Collections.addAll(one, "迪丽热巴", "周雨彤", "马思纯", "肖战", "老子", "庄子");

        one.stream().filter((String s) -> {
            return s.length() == 3;
        }).forEach(System.out::println);

        System.out.println("---------------------");

        //简化
        one.stream().filter(s -> s.length() == 3).forEach(System.out::println);
        System.out.println("---------------------");

stream流中的limit方法:

//限制输出数据数量

            one.stream()
                .limit(3)
                .forEach(System.out::println);

stream流中的skip方法:

List<String> one = new ArrayList<>();
        Collections.addAll(one, "迪丽热巴", "周雨彤", "马思纯", "肖战", "老子", "庄子");

        //跳过指定的前两个数据
        one.stream()
                .skip(2)
                .forEach(System.out::println);

从下面可以看到skip指定类型是long,所以不能指定跳过某一个String。 

 Stream流中的map方法:

@Test
    public void testMap() {
        //Map可以将一种类型的流转为另一种类型的流
        Stream<String> original = Stream.of("11", "22", "33");
        //将stream流中的字符串转为Integer
        //参数就是你原本的类型
//        original.map((String s) -> {
//            return Integer.parseInt(s);
//        });
        System.out.println("---------------------");
        //简化
        //      original.map(s -> Integer.parseInt(s)).forEach(System.out::println);
        //再简化
        original.map(Integer::parseInt).forEach(System.out::println);
    }

stream流中的sorted方法

//排序

@Test
    public void testSorted() {
        // sorted(): 根据元素的自然顺序排序
        // sorted(Comparator<? super T> comparator): 根据比较器指定的规则排序
        Stream<Integer> stream = Stream.of(33, 22, 11, 55);
        //升序
        stream.sorted().forEach(System.out::println);

        System.out.println("------------------------");
        //降序
        stream.sorted((Integer i1, Integer i2) -> {
            return i2 - i1;
        }).forEach(System.out::println);

        System.out.println("------------------------");
        //降序简化
        stream.sorted((i1, i2) -> i2 - i1).forEach(System.out::println);
    }

Stream流中的distinct方法:

// distinct对自定义对象去除重复
    @Test
    public void testDistinct() {
        Stream<Integer> stream = Stream.of(33, 22, 11, 55, 88, 33, 22, 22, 88, 34, 23);
        stream.distinct().forEach(System.out::println);

        Stream<String> stream1 = Stream.of("a", "b", "c", "a", "b");
        stream1.distinct().forEach(System.out::println);
    }

对Person类中的equals和hashcode方法进行重写,stream中的数据再运行时就会被去重

@Test
    public void testDistinct01() {
        Stream<Person> stream = Stream.of(
                new Person("貂蝉", 18),
                new Person("杨玉环", 20),
                new Person("杨玉环", 20),
                new Person("西施", 16),
                new Person("西施", 16),
                new Person("王昭君", 25)
        );

        stream.distinct().forEach(System.out::println);
    }

重写Person类中的equals和hashcode方法:

运行结果:

Stream流的match方法:

@Test
    public void testMatch() {
        Stream<Integer> stream = Stream.of(33, 22, 11, 55, 88, 33, 22, 22, 88, 34, 23);
        //allMatch需要所有的元素都满足才返回true
        //allMatch:匹配所有元素,所有的元素都需要满足条件
        boolean b = stream.allMatch((Integer i) -> {
            return i > 22;
        });
        System.out.println(b);

        Stream<Integer> stream1 = Stream.of(11, 2, 4, 5);
        //allMatch需要所有的元素都满足才返回true
        boolean b1 = stream1.allMatch((Integer i) -> {
            return i > 0;
        });
        System.out.println(b1);

        //anyMatch: 匹配某个元素,只要有其中一个元素满足条件即可
        Stream<Integer> stream3 = Stream.of(33, 22, 11, 55, 88, 33, 22, 22, 88, 34, 23);
        boolean b2 = stream3.anyMatch((Integer i) -> {
            return i > 22;
        });
        System.out.println(b2);

        //noneMatch: 匹配所有元素,所有元素都不满足条件
        Stream<Integer> stream4 = Stream.of(33, 22, 11, 55, 88, 33, 22, 22, 88, 34, 23);
        boolean b3 = stream4.noneMatch(i -> i > 0);
        System.out.println(b3);
    }

Stream流的find方法:

@Test
    public void testFind() {
        Stream<Integer> stream = Stream.of(33, 22, 11, 55, 88, 33, 22, 22, 88, 34, 23);
        Optional<Integer> optional = stream.findFirst();
        System.out.println(optional.get());
    }

Stream流中的max和min方法:

@Test
    public void testMax() {
        //获取最大值
        Stream<Integer> stream = Stream.of(33, 22, 11, 55, 88, 33, 22, 22, 88, 34, 23);
        Optional<Integer> max = stream.max((o1, o2) -> o1 - o2);
        System.out.println(max.get());
        //获取最小值
        Optional<Integer> min = Stream.of(5, 6, 3, 1).min((o1, o2) -> o1 - o2);
        System.out.println(min.get());
    }

输出: 

 Stream流的reduce方法:

        // T reduce(T identity, BinaryOperator<T> accumulator);
        // T identity: 默认值
        // BinaryOperator<T> accumulator: 对数据进行处理的方式
        // reduce如何执行?
        // 第一次, 将默认值赋值给x, 取出集合第一元素赋值给y
        // 第二次, 将上一次返回的结果赋值x, 取出集合第二元素赋值给y
        // 第三次, 将上一次返回的结果赋值x, 取出集合第三元素赋值给y
        // 第四次, 将上一次返回的结果赋值x, 取出集合第四元素赋值给y
        //以此类推
@Test
    public void testReduce() {
        int reduce = Stream.of(4, 5, 7, 2, 9).reduce(0, (x, y) -> {
            System.out.println("x = " + x + " y = " + y);
            return x + y;
        });
        System.out.println(reduce);
    }

有点类似于js的特性。

27即为数据和。

找出最大值:

int max = Stream.of(4, 5, 7, 2, 9).reduce(0, (x, y) -> {
            return x > y ? x : y;
        });
        System.out.println(max);

对stream里面封装对象里的某一个数据进行求和:

@Test
    public void testReduce01() {
        Integer totalAge = Stream.of(
                new Person("刘德华", 58),
                new Person("张学友", 56),
                new Person("郭富城", 54),
                new Person("黎明", 52))
                .map((p) -> {
                    return p.getAge();
                }).reduce(0, (x, y) -> {
                    return x + y;
                });
        System.out.println("totalAge= " + totalAge);
    }

 求stream内封装对象某一个属性最大值

Integer maxAge = Stream.of(
                new Person("刘德华", 58),
                new Person("张学友", 56),
                new Person("郭富城", 54),
                new Person("黎明", 52))
                .map(p -> p.getAge())
                .reduce(0, Math::max);
        System.out.println("maxAge=" + maxAge);

统计某一个元素出现的次数:

//统计a出现的次数
        Integer count = Stream.of("a", "b", "a", "d", "a")
                .map(s -> {
                    if (s == "a") {
                        return 1;
                    } else {
                        return 0;
                    }
                })
                .reduce(0, Integer::sum);
        System.out.println("count=" + count);

Stream的concat方法:

@Test
    public void testContact() {
        Stream<String> streamA = Stream.of("张三");
        Stream<String> streamB = Stream.of("李四");

        //合并成一个流
        Stream<String> newStream = Stream.concat(streamA, streamB);
        // 注意:合并流之后,不能操作之前的流啦.
        // streamA.forEach(System.out::println);
        newStream.forEach(System.out::println);
    }

Stream小练习:

public static void main(String[] args) {
        // 第一个队伍
        List<String> one = new ArrayList<>();
        Collections.addAll(one, "迪丽热巴", "宋远桥", "苏星河", "老子", "庄子", "孙子", "洪七公");
        // 第二个队伍
        List<String> two = new ArrayList<>();
        Collections.addAll(two, "古力娜扎", "张无忌", "张三丰", "赵丽颖", "张二狗", "张天爱", "张三");

        // 1.第一个队伍只要名字为3个字的成员姓名;
        System.out.println("1.第一个队伍只要名字为3个字的成员姓名-----------------------");
        one.stream().filter(s -> s.length() == 3).forEach(System.out::println);

        // 2.第一个队伍筛选之后只要前3个人;
        System.out.println("2.第一个队伍筛选之后只要前3个人-----------------------");
        one.stream().limit(3).forEach(System.out::println);

        // 3.第二个队伍只要姓张的成员姓名;
        System.out.println("3.第二个队伍只要姓张的成员姓名-----------------------");
        two.stream().filter(s -> s.startsWith("张")).forEach(System.out::println);

        // 4.第二个队伍筛选之后不要前2个人;
        System.out.println("4.第二个队伍筛选之后不要前2个人-----------------------");
        two.stream().skip(2).forEach(System.out::println);

        // 5.将两个队伍合并为一个队伍;
        System.out.println("5.将两个队伍合并为一个队伍-----------------------");
        Stream<String> newStream = Stream.concat(one.stream(), two.stream());
        newStream.forEach(System.out::println);

        // 6.根据姓名创建`Person`对象;
        // 7.打印整个队伍的Person对象信息。
        System.out.println("6.根据姓名创建`Person`对象-----------------------");
        System.out.println("7.打印整个队伍的Person对象信息-----------------------");
        Stream<String> StreamAB = Stream.concat(one.stream(), two.stream());
        StreamAB.map(Person::new).forEach(System.out::println);
    }

输出:

将流中的数据收集到集合中

//将流中的数据收集到集合中
    @Test
    public void testStreamToCollection() {
        Stream<String> stream = Stream.of("aa", "bb", "cc", "aa");

        //将流中的数据收集到集合中
        //collection收集流中的数据到集合中
//        List<String> list = stream.collect(Collectors.toList());
//        System.out.println("list = " + list);

//        Set<String> set = stream.collect(Collectors.toSet());
//        System.out.println("set = " + set);

        HashSet<String> hashSet = stream.collect(Collectors.toCollection(HashSet::new));
        System.out.println("hashset = " + hashSet);
    }

将流中的数据收集到数组中:

@Test
    public void testStreamToArray() {
        // 转成Object数组不方便
        // Object[] objects = stream.toArray();
        // for (Object o : objects) {
        //     System.out.println("o = " + o);
        // }
        // String[]
        Stream<String> stream = Stream.of("aa", "bb", "cc", "aa");
        String[] strings = stream.toArray(String[]::new);
        System.out.println("strings = " + Arrays.toString(strings) + ", 长度:" + strings.length);

    }

对流中数据进行聚合运算:

@Test
    public void testStreamToOther() {
        Stream<Student> studentStream = Stream.of(
                new Student("赵丽颖", 58, 95),
                new Student("杨颖", 56, 88),
                new Student("迪丽热巴", 56, 99),
                new Student("柳岩", 52, 77));
        //获取最大值
        Optional<Student> max = studentStream.collect(Collectors.maxBy((s1, s2) -> s1.getSocre() - s2.getSocre()));
        System.out.println(max.get());

        List<Student> max1 = new ArrayList<>();
        Collections.addAll(max1, new Student("赵丽颖", 58, 95),
                new Student("杨颖", 56, 88),
                new Student("迪丽热巴", 56, 99),
                new Student("柳岩", 52, 77));
        Optional<Student> collect = max1.stream().collect(Collectors.maxBy((s1, s2) -> s1.getSocre() - s2.getSocre()));
        System.out.println(collect.get());

        //获取最小值
        Stream<Student> studentStream1 = Stream.of(
                new Student("赵丽颖", 58, 95),
                new Student("杨颖", 56, 88),
                new Student("迪丽热巴", 56, 99),
                new Student("柳岩", 52, 77));
        Optional<Student> min = studentStream1.collect(Collectors.maxBy((s1, s2) -> s2.getSocre() - s1.getSocre()));
        System.out.println(min.get());

        //求总和
        Stream<Student> studentStream2 = Stream.of(
                new Student("赵丽颖", 58, 95),
                new Student("杨颖", 56, 88),
                new Student("迪丽热巴", 56, 99),
                new Student("柳岩", 52, 77));
        Integer sum = studentStream2.collect(Collectors.summingInt(s -> s.getAge()));
        System.out.println("sum = " + sum);

        // 平均值
        Stream<Student> studentStream3 = Stream.of(
                new Student("赵丽颖", 58, 95),
                new Student("杨颖", 56, 88),
                new Student("迪丽热巴", 56, 99),
                new Student("柳岩", 52, 77));
        //       Double avg = studentStream3.collect(Collectors.averagingInt(s -> s.getSocre()));
        Double avg = studentStream3.collect(Collectors.averagingInt(Student::getSocre));
        System.out.println("平均值: " + avg);

        // 统计数量
        Stream<Student> studentStream4 = Stream.of(
                new Student("赵丽颖", 58, 95),
                new Student("杨颖", 56, 88),
                new Student("迪丽热巴", 56, 99),
                new Student("柳岩", 52, 77));
        Long count = studentStream4.collect(Collectors.counting());
        System.out.println("统计数量: " + count);
    }

输出:

对流中数据进行分组:

@Test
    public void testCollectors() {
        Stream<Student> studentStream5 = Stream.of(
                new Student("赵丽颖", 58, 95),
                new Student("杨颖", 56, 88),
                new Student("迪丽热巴", 56, 99),
                new Student("柳岩", 52, 77));
        Map<Integer, List<Student>> map = studentStream5.collect(Collectors.groupingBy((s) -> s.getAge()));
        map.forEach((k, v) -> {
            System.out.println(k + "::" + v);
        });
    }

输出:

@Test
    public void testCollectors01() {
        Stream<Student> studentStream5 = Stream.of(
                new Student("赵丽颖", 58, 95),
                new Student("杨颖", 56, 88),
                new Student("迪丽热巴", 56, 99),
                new Student("柳岩", 52, 56));
        Map<String, List<Student>> map = studentStream5.collect(Collectors.groupingBy((s) -> {
            if (s.getSocre() > 60) {
                return "及格";
            } else {
                return "不及格";
            }
        }));
        map.forEach((k, v) -> {
            System.out.println(k + "::" + v);
        });
    }

 输出:

 多级分组:

// 多级分组
    @Test
    public void testCustomGroup() {
        Stream<Student> studentStream = Stream.of(
                new Student("赵丽颖", 52, 95),
                new Student("杨颖", 56, 88),
                new Student("迪丽热巴", 56, 55),
                new Student("柳岩", 52, 33));

        // 先根据年龄分组,每组中在根据成绩分组
        // groupingBy(Function<? super T, ? extends K> classifier, Collector<? super T, A, D> downstream)
        Map<Integer, Map<String, List<Student>>> map = studentStream.collect(Collectors.groupingBy(Student::getAge, Collectors.groupingBy((s) -> {
            if (s.getSocre() > 60) {
                return "及格";
            } else {
                return "不及格";
            }
        })));

        // 遍历
        map.forEach((k, v) -> {
            System.out.println(k);
            // v还是一个map,再次遍历
            v.forEach((k2, v2) -> {
                System.out.println("\t" + k2 + " == " + v2);
            });
        });
    }

输出:

对流中数据进行拼接:

@Test
    public void testCollection01() {
        Stream<Student> studentStream = Stream.of(
                new Student("赵丽颖", 52, 95),
                new Student("杨颖", 56, 88),
                new Student("迪丽热巴", 56, 55),
                new Student("柳岩", 52, 33));

        // 根据一个字符串拼接: 赵丽颖__杨颖__迪丽热巴__柳岩
        //    String names = studentStream.map(Student::getName).collect(Collectors.joining("__"));
        String names = studentStream.map(Student::getName).collect(Collectors.joining("___", "+", "-"));
        System.out.println(names);
    }

输出:

Optional类的基本使用:

@Test
    public void test01() {
        // 1.创建Optional对象
        // of:只能传入一个具体值,不能传入null
        // ofNullable: 既可以传入具体值,也可以传入null
        // empty: 存入的是null
        Optional<String> op1 = Optional.of("凤姐");
        // Optional<String> op1 = Optional.of(null);
        // Optional<String> op2 = Optional.ofNullable("如花");
        // Optional<String> op2 = Optional.ofNullable("如花");
        Optional<Object> op3 = Optional.empty();

        // 2.isPresent: 判断Optional中是否有具体值, 有值返回true,没有值返回false
        // boolean present = op1.isPresent();
        // System.out.println("present = " + present);

        // 3.get: 获取Optional中的值,如果有值就返回值具体值,没有值就报错
        // System.out.println(op3.get());

        if (op1.isPresent()) {
            System.out.println(op1.get());
        } else {
            System.out.println("没有值");
        }
    }
@Test
    public void test02() {
        // Optional<String> userNameO = Optional.of("凤姐");
        Optional<String> userNameO = Optional.empty();//name = 如花吗?
        //       Optional<String> userNameO = Optional.of(" ");//name =

        // orElse: 如果Optional中有值,就取出这个值,如果没有值就使用参数指定的值
        String name = userNameO.orElse("如花吗?");
        System.out.println("name = " + name);
    }
@Test
    public void test04() {
        Optional<String> userNameO = Optional.of("凤姐");
        // Optional<String> userNameO = Optional.empty();

        // 存在做的什么
        // ifPresent: 如果有值就调用参数
        /*userNameO.ifPresent(s -> {
            System.out.println("有值: " + s);
        });*/

        // ifPresentOrElse: 存在做的什么,不存在做点什么
        userNameO.ifPresentOrElse(s -> {
            System.out.println("有值: " + s);
        }, () -> {
            System.out.println("没有值");
        });
    }

就这些吧。

🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉












总结:啊,最近好烦,我的爱车坏掉了,一直没找到时间去修,还有2个事情眼看时间期限临近,再加上上课时无缘无故的老是神游,呜呜呜呜呜呜呜呜,我是真的会谢,还有这学习计划,还有别人在前面跑,我在后面追,还追不上,呜呜呜呜呜呜呜呜,我还在用一个实战项目练手,正项目耽误了不少时间了,呜呜呜呜呜我真的谢了。。。。

还有就是最近迷上了各种算法加密。

还有一些人际关系是真的令我好烦,暂时还找不到好的解决方法,不过有一些是肯定无疑的。唉,跟着自己的感觉走吧,也不赖。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雾喔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值