复习Stream流,函数式接口,方法引用

打印 上一主题 下一主题

主题 530|帖子 530|积分 1590

今天对这些内容进行了一个复习,以写demo加做笔记的形式

stream能够更加优雅的处理集合、数组等数据,让我们写出更加直观、可读性更高的数据处理代码
创建steam流的方式

set、list能够直接通过.stream()的形式创建steam流
而数组需要通过 Arrays.stream(arr); Stream.of(arr);
map需要通过entrySet()方法,先将map转换成Set set对象,再通过set.stream()的方式转换
stream中的api比较多
  1. /**
  2. * @author Pzi
  3. * @create 2022-12-30 13:22
  4. */
  5. @SpringBootTest
  6. @RunWith(SpringRunner.class)
  7. public class Test2 {
  8.     @Test
  9.     public void test1() {
  10.         List<Author> authors = S.getAuthors();
  11.         authors
  12.                 .stream()
  13.                 .distinct()
  14.                 .filter(author -> {
  15.                     // 满足这个条件,那么才会被筛选到继续留在stream中
  16.                     return author.getAge() < 18;
  17.                 })
  18.                 .forEach(author -> System.out.println(author.getAge()));
  19.     }
  20.     // 对双列集合map的stream操作
  21.     @Test
  22.     public void test2() {
  23.         Map<String, Integer> map = new HashMap<>();
  24.         map.put("蜡笔小新", 19);
  25.         map.put("黑子", 17);
  26.         map.put("日向翔阳", 16);
  27.         //entrySet是一个包含多个Entry的Set数据结构,Entry是key-val型的数据结构
  28.         Set<Map.Entry<String, Integer>> entries = map.entrySet();
  29.         entries.stream()
  30.                 .filter(entry -> {
  31.                     return entry.getValue() > 17;
  32.                 })
  33.                 .forEach(entry -> {
  34.                     System.out.println(entry);
  35.                 });
  36.     }
  37.     // stream的map操作,提取stream中对象的属性,或者计算
  38.     @Test
  39.     public void test3() {
  40.         List<Author> authors = S.getAuthors();
  41.         authors
  42.                 .stream()
  43.                 .map(author -> author.getName())
  44.                 .forEach(name -> System.out.println(name));
  45.         System.out.println(1);
  46.         authors
  47.                 .stream()
  48.                 .map(author -> author.getAge())
  49.                 .map(age -> age + 10)
  50.                 .forEach(age -> System.out.println(age));
  51.     }
  52.     // steam的sorted操作
  53.     @Test
  54.     public void test4() {
  55.         List<Author> authors = S.getAuthors();
  56.         authors
  57.                 .stream()
  58.                 .distinct()
  59.                 .sorted(((o1, o2) -> o2.getAge() - o1.getAge()))
  60.                 .skip(1)
  61.                 .forEach(author -> System.out.println(author.getName() + " " + author.getAge()));
  62.     }
  63.     // flapMap的使用,重新组装,改变stream流中存放的对象
  64.     @Test
  65.     public void test5() {
  66.         //        打印所有书籍的名字。要求对重复的元素进行去重。
  67.         List<Author> authors = S.getAuthors();
  68.         authors.stream()
  69.                 .flatMap(author -> author.getBooks().stream())
  70.                 .distinct()
  71.                 .forEach(book -> System.out.println(book.getName()));
  72.         authors.stream()
  73.                 // 将以authors为对象的stream流 组装成 以book为对象的strem流
  74.                 .flatMap(author -> author.getBooks().stream())
  75.                 .distinct()
  76.                 // 将每个book中的category转换成数组,然后将[x1,x2]代表分类的数组转换成stream流,然后使用flapMap将该数组stream流组装成以x1,x2...为对象的stream流
  77.                 // 将以book为对象的strem流 组装成 以category为对象的stream流
  78.                 .flatMap(book -> Arrays.stream(book.getCategory().split(",")))
  79.                 .distinct()
  80.                 .forEach(category -> System.out.println(category));
  81.     }
  82.     // 数组转换成stream流
  83.     @Test
  84.     public void test6() {
  85.         Integer[] arr = {1, 2, 3, 4, 5};
  86.         Stream<Integer> stream = Arrays.stream(arr);
  87.         stream
  88.                 .filter(integer -> integer > 3)
  89.                 .forEach(integer -> System.out.println(integer));
  90.     }
  91.     @Test
  92.     public void test7() {
  93. //        打印这些作家的所出书籍的数目,注意删除重复元素。
  94.         List<Author> authors = S.getAuthors();
  95.         long count = authors
  96.                 .stream()
  97.                 .flatMap(author -> author.getBooks().stream())
  98.                 .distinct()
  99.                 .count();
  100.         System.out.println(count);
  101.     }
  102.     // max() min()
  103.     @Test
  104.     public void test8() {
  105. //        分别获取这些作家的所出书籍的最高分和最低分并打印。
  106.         List<Author> authors = S.getAuthors();
  107.         Optional<Integer> max = authors.stream()
  108.                 .flatMap(author -> author.getBooks().stream())
  109.                 .map(book -> book.getScore())
  110.                 .max((score1, score2) -> score1 - score2);
  111.         Optional<Integer> min = authors.stream()
  112.                 .flatMap(author -> author.getBooks().stream())
  113.                 .map(book -> book.getScore())
  114.                 .min((score1, score2) -> score1 - score2);
  115.         System.out.println(max.get());
  116.         System.out.println(min.get());
  117.     }
  118.     // stream 的 collect()
  119.     @Test
  120.     public void test9() {
  121.         // 获取所有作者名字
  122.         List<Author> authors = S.getAuthors();
  123.         Set<String> collect = authors.stream()
  124.                 .map(author -> author.getName())
  125.                 .collect(Collectors.toSet());
  126.         System.out.println(collect);
  127.         //获取一个所有书名的Set集合。
  128.         Set<String> collect1 = authors.stream()
  129.                 .flatMap(author -> author.getBooks().stream())
  130.                 .map(book -> book.getName())
  131.                 .collect(Collectors.toSet());
  132.         System.out.println(collect1);
  133.         //        获取一个Map集合,map的key为作者名,value为List<Book>
  134.         Map<String, List<Book>> collect2 = authors.stream()
  135.                 .distinct()
  136.                 .collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
  137.         System.out.println(collect2);
  138.     }
  139.     // anyMatch
  140.     @Test
  141.     public void test10() {
  142.         List<Author> authors = S.getAuthors();
  143.         boolean b = authors.stream()
  144.                 .anyMatch(author -> author.getAge() > 29);
  145.         System.out.println(b);
  146.     }
  147.     // allMatch
  148.     @Test
  149.     public void test11() {
  150.         List<Author> authors = S.getAuthors();
  151.         boolean b = authors.stream()
  152.                 .allMatch(author -> author.getAge() > 18);
  153.         System.out.println(b);
  154.     }
  155.     // findFirst
  156.     @Test
  157.     public void test12() {
  158.         List<Author> authors = S.getAuthors();
  159.         Optional<Author> first = authors.stream()
  160.                 .sorted(((o1, o2) -> o1.getAge() - o2.getAge()))
  161.                 .findFirst();
  162.         first.ifPresent(author -> System.out.println(author));
  163.     }
  164.     // reduce() 的使用
  165.     @Test
  166.     public void test13() {
  167.         //        使用reduce求所有作者年龄的和
  168.         List<Author> authors = S.getAuthors();
  169.         Integer sum = authors.stream()
  170.                 .distinct()
  171.                 .map(author -> author.getAge())
  172.                 .reduce(0, (result, element) -> result + element);
  173. //                .reduce(0, (result, element) -> result + element);
  174.         System.out.println(sum);
  175.     }
  176.     @Test
  177.     public void test14() {
  178.         //        使用reduce求所有作者中年龄的最小值
  179.         List<Author> authors = S.getAuthors();
  180.         Integer minAge = authors.stream()
  181.                 .map(author -> author.getAge())
  182.                 .reduce(Integer.MAX_VALUE, (res, ele) -> res > ele ? ele : res);
  183.         System.out.println(minAge);
  184.     }
  185.     // 没有初始值的reduce()使用
  186.     @Test
  187.     public void test15() {
  188.         List<Author> authors = S.getAuthors();
  189.         Optional<Integer> age = authors.stream()
  190.                 .map(author -> author.getAge())
  191.                 .reduce((res, ele) -> res > ele ? ele : res);
  192.         System.out.println(age.get());
  193.     }
  194.     // Optional对象的封装,orElseGet的使用
  195.     @Test
  196.     public void test16() {
  197.         Optional<Author> authorOptional = Optional.ofNullable(null);
  198.         Author author1 = authorOptional.orElseGet(() -> new Author(1l, "1", 1, "1", null));
  199.         System.out.println(author1);
  200. //        authorOptional.ifPresent(author -> System.out.println(author.getName()));
  201.     }
  202.     @Test
  203.     public void test17() {
  204.         Optional<Author> authorOptional = Optional.ofNullable(null);
  205.         try {
  206.             Author author = authorOptional.orElseThrow((Supplier<Throwable>) () -> new RuntimeException("exception"));
  207.             System.out.println(author.getName());
  208.         } catch (Throwable throwable) {
  209.             throwable.printStackTrace();
  210.         }
  211.     }
  212.     // Optional的filter()方法
  213.     // ifPresent()可以安全消费Optional中包装的对象
  214.     @Test
  215.     public void test18() {
  216.         Optional<Author> optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));
  217.         optionalAuthor
  218.                 .filter(author -> author.getAge() > 14)
  219.                 .ifPresent(author -> System.out.println(author));
  220.     }
  221.     // Optional的isPresent()方法,用来判断该Optional是否包装了对象
  222.     @Test
  223.     public void test19() {
  224.         Optional<Author> optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));
  225.         boolean present = optionalAuthor.isPresent();
  226.         if (present) {
  227.             System.out.println(optionalAuthor.get().getName());
  228.         }
  229.     }
  230.     //  Optional的map(),将一个 Optional 转换成另一个 Optional
  231.     @Test
  232.     public void test20() {
  233.         Optional<Author> optionalAuthor = Optional.ofNullable(S.getAuthors().get(0));
  234.         optionalAuthor.ifPresent(author -> System.out.println(author.getBooks()));
  235.         Optional<List<Book>> books = optionalAuthor.map(author -> author.getBooks());
  236.         books.ifPresent(books1 -> System.out.println(books.get()));
  237.     }
  238.     // 类的静态方法
  239.     @Test
  240.     public void test21() {
  241.         List<Author> authors = S.getAuthors();
  242.         authors.stream()
  243.                 .map(author -> author.getAge())
  244.                 .map(integer -> String.valueOf(integer));
  245.         // lambda方法体中只有一行代码
  246. //                .map(String::valueOf);
  247.     }
  248.     // 对象的实例方法
  249.     @Test
  250.     public void test22() {
  251.         List<Author> authors = S.getAuthors();
  252.         Stream<Author> authorStream = authors.stream();
  253.         StringBuilder sb = new StringBuilder();
  254.         authorStream.map(author -> author.getName())
  255.                 // lambda方法体中只有一行代码,且将参数全部按照顺序传入这个重写方法中
  256.                 .forEach(str -> sb.append(str));
  257.     }
  258.     // 接口中只有一个抽象方法称为函数式接口
  259.     // 方法引用的条件是:lambda方法体中只有一行方法
  260.     // 构造器的方法引用
  261.     @Test
  262.     public void test23() {
  263.         List<Author> authors = S.getAuthors();
  264.         authors.stream()
  265.                 .map(Author::getName)
  266.                 .map(StringBuilder::new)
  267.                 .map(stringBuilder -> stringBuilder.append("abc"))
  268.                 .forEach(System.out::println);
  269.     }
  270.     // steam提供的处理基本数据类型,避免频繁的自动拆/装箱,从而达到省时,提高性能
  271.     @Test
  272.     public void test24() {
  273.         List<Author> authors = S.getAuthors();
  274.         authors.stream()
  275.                 .map(author -> author.getAge())
  276.                 .map(age -> age + 10)
  277.                 .filter(age -> age > 18)
  278.                 .map(age -> age + 2)
  279.                 .forEach(System.out::println);
  280.         authors.stream()
  281.                 .mapToInt(author -> author.getAge())
  282.                 .map(age -> age + 10)
  283.                 .filter(age -> age > 18)
  284.                 .map(age -> age + 2)
  285.                 .forEach(System.out::println);
  286.     }
  287.     @Test
  288.     public void test25() {
  289.         List<Author> authors = S.getAuthors();
  290.         authors.stream()
  291.                 .parallel()
  292.                 .map(author -> author.getAge())
  293.                 .peek(integer -> System.out.println(integer+" "+Thread.currentThread().getName()))
  294.                 .reduce(new BinaryOperator<Integer>() {
  295.                     @Override
  296.                     public Integer apply(Integer result, Integer ele) {
  297.                         return result + ele;
  298.                     }
  299.                 }).ifPresent(sum -> System.out.println(sum));
  300.     }
  301. }
复制代码
lambda表达式

lambda表达式只关心 形参列表 和 方法体
用在重写抽象方法的时候,一般都是采用lambda表达式的方式来重写
函数式接口

函数式接口:接口中只有一个抽象方法,就称之为函数式接口。在Java中Consumer,Funciton,Supplier
方法引用

方法引用:当lambda表达式的方法体中只有一行代码,并且符合一些规则,就可以将该行代码转换成方法引用的形式
可以直接使用idea的提示自动转换
这只是一个语法糖,能看懂代码就行,不要过于纠结

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

半亩花草

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表