Lambda表达式使用2

时间:2022-09-16 18:53:52

  1.概述
  
  本篇主要介绍lambda中常用的收集器,收集器的作用就是从数据流中生成需要的数据接口。
  
  最常用的就是Collectors.toList(),只要将它传递给collect()函数,就能够使用它了。
  
  在我们使用收集器的时候经常会用到“方法引用”这样的简写语法:
  
  方法引用:ClassName::methodName
  
  2.代码示例
  
  按照收集器的作用分类
  
  公共代码:
  
  @Data
  
  @NoArgsConstructor
  
  @AllArgsConstructor
  
  public class Artist {
  
  private String name;
  
  private String age;
  
  private boolean isMan;
  
  List<Artist> artists = Lists.newArrayList();
  
  Artist artist1 = new Artist("kido", "28", false);
  
  Artist artist2 = new Artist("tom", "23", true);
  
  Artist artist3 = new Artist("whale", "22", false);
  
  Artist artist4 = new Artist("jack", "26", true);
  
  artists.add(artist1);
  
  artists.add(artist2);
  
  artists.add(artist3);
  
  artists.add(artist4);
  
  // 1.方法引用:ClassName::methodName
  
  List<String> list = artists.stream().map(Artist::getName).collect(Collectors.toList());
  
  list.forEach(name -www.michenggw.com> System.out.println(name));
  
  // 2.元素顺序,集合有序流就有序,集合无序流也无序,使用sorted()可以使得流变得有序
  
  Set<Integer> numbers = new HashSet<>(Arrays.asList(4, 3, 2, 1, 6, 9, 8, 10));
  
  numbers.stream().forEach(x -> System.out.println(x));
  
  System.out.println("---------------------------");
  
  List<Integer> numbersOrder = numbers.stream().sorted().collect(Collectors.toList());
  
  numbersOrder.forEach(x -> System.out.println(x));
  
  // 3.使用收集器, toList() toSet()等
  
  Set<String> set = artists.stream().map(Artist::getName).collect(Collectors.toSet());
  
  set.forEach(x ->yongshiyule178.com/ System.out.println(x));
  
  Map<String, String> map = artists.stream(www.quwanyule157.com ).collect(Collectors.toMap(Artist::getName, Artist::getAge));
  
  map.forEach((key, value) -> System.out.println(key + "<--->" + value));
  
  // 4.转换成值, 找出年龄最大的
  
  Optional<Artist> collect = artists.stream().collect(Collectors.maxBy(Comparator.comparing(item -> item.getAge())));
  
  System.out.println(collect.get());
  
  // 5.数据分块, Predicate对象为true和false
  
  Map<Boolean, List<Artist>> map2 = artists.stream().collect(Collectors.partitioningBy(Artist::isMan));
  
  map2.forEach((key, value) -> {System.out.println(key + "<--->" +value);});
  
  // 6.数据分组,按照姓名分组
  
  Map<String, List<Artist>> map3 = artists.stream().collect(Collectors.groupingBy(Artist::getAge));
  
  map3.forEach((key, value) -> {System.out.println(key + "<--->" +value);});
  
  // 7.字符串,将收集流中的数据生成字符串
  
  String string = artists.stream().map(item www.mhylpt.com/ -> item.getName()).collect(Collectors.joining(", ", "[", "]"));
  
  System.out.println(string);
  
  // 8.组合收集器, 使用groupingBy先分组在计数
  
  Map<Boolean, Long> map4 = artists.stream().collect(Collectors.groupingBy(Artist::isMan, Collectors.counting()));
  
  map4.forEach((key, value) -> {System.out.println(key + "<--->" +value);});