首页 > 编程语言 >函数式编程-Stream流

函数式编程-Stream流

时间:2024-08-08 22:50:40浏览次数:6  
标签:Stream 函数 stream author 编程 System authors new out

一、函数式编程-Stream流

1、概述

1.1 为什么学?

  • 能够看懂公司里的代码
  • 大数量下处理集合效率高
  • 代码可读性高
  • 消灭嵌套地狱

普通写法与函数式编程写法对比:

普通写法

//查询未成年作家的评分在70以上的书籍 由于洋流影响所以作家和书籍可能出现重复,需要进行去重
        List<Book> bookList = new ArrayList<>();
        Set<Book> uniqueBookValues = new HashSet<>();
        Set<Author> uniqueAuthorValues = new HashSet<>();
        for (Author author : authors) {
            if (uniqueAuthorValues.add(author)) {
                if (author.getAge() < 18) {
                    List<Book> books = author.getBooks();
                    for (Book book : books) {
                        if (book.getscore() > 70) {
                            if (uniqueBookValues.add(book)) {
                                bookList.add(book);
                            }
                        }
                    }
                }
            }
        }
    }
    System.out.printin(bookList);

函数式编程

		List<Book> co1lect= authors.stream()
                .distinct()
                .fiter(author > author.getAge()< 18)
                .map(author -> author.getBooks())
                .flatMap(co1lection::stream).
                filter(book -> book.getscore()> 70)
                .distinct()
                .co11ect(co1lectors.toList());
        System.out.printin(co1lect);

1.2 函数式编程思想

1.2.1 概念

面向对象思想需要关注用什么对象完成什么事情。而函数式编程思想就类似于我们数学中的函数。他主要关注的是对数据进行了什么操作。

1.2.2 优点

  • 代码简介,开发快速
  • 接近自然语言,易于理解
  • 易于”并发编程“,适合大数据量,效率较高

1.3 适用场景:与普通循环比较有什么优劣?

普通循环(如for循环)与Java的Stream API在性能上的比较并不是绝对的,它们各自具有不同的优势和适用场景。下面是一些关于两者性能、优劣以及适用场景的比较:

1.3.1性能

  • 小型数据集:对于小型数据集,普通循环通常性能更好。因为普通循环直接操作数组或集合元素,没有额外的对象创建和函数调用开销。
  • 大型数据集:对于大型数据集,Stream API的并行处理能力(通过parallelStream())可能会带来性能优势,特别是当任务可以高度并行化执行时。然而,并行处理也涉及到线程管理、任务拆分和合并等额外开销,所以在某些情况下,普通循环可能仍然更快。
  • 数据操作复杂性:对于复杂的数据转换和过滤操作,Stream API提供了更简洁和易读的语法。虽然这可能带来一些性能开销,但在许多情况下,这种开销是可以接受的。

1.3.2优劣

  • 普通循环:

    • 优势:性能较好,特别是对于小型数据集;代码更直接和简单;没有额外的对象创建和函数调用开销。
    • 劣势:对于复杂的数据转换和过滤操作,代码可能不够简洁和易读;不支持并行处理(除非手动实现)。
  • Stream API:

    • 优势:提供了声明式编程风格,代码更简洁和易读;支持并行处理,可以充分利用多核处理器;适用于复杂的数据转换和过滤操作。
    • 劣势:可能带来额外的性能开销,特别是对于小型数据集;不总是提供最佳性能,尤其是在任务不是高度并行或存在数据竞争的情况下。

1.3.3适用场景

  • 普通循环:
    • 当处理小型数据集时;
    • 当需要直接操作数组或集合元素时;
    • 当性能是关键因素且任务不适合并行处理时。
  • Stream API:
    • 当处理大型数据集且任务可以高度并行化执行时;
    • 当需要执行复杂的数据转换和过滤操作时;
    • 当代码的可读性和简洁性比性能更重要时。

综上所述,选择使用普通循环还是Stream API取决于具体的应用场景和性能需求。在性能敏感的场景中,最好进行基准测试以确定哪种方式更适合你的特定用例。

2、 Lambda表达式

2.1 概述

  • Lambda是JDK8中一个语法糖。他可以对某些匿名内部类的写法进行简化。它是函数式编程思想的一个重要体现。让我们不用关注是什么对象。而是更关注我们对数据进行了什么操作。

  • 那我们什么时候才能对匿名内部类进行简化呢?原则是:匿名内部类是一个接口、并且其中只有一个抽象方法需要被重写。

2.2 核心原则

可推导可省略

2.3 基本格式

(参数列表)-> {代码}

下面的举例,方法的参数都是一个接口,且该接口只有一个抽象类。

  • 例一
new Thread(new Runnable(){
      @Override
      public void run() {
            System.out.println("新线程中run方法被执行了");
      }
}).start();

可以使用Lambda的格式对其进行修改。修改后如下:lambda表达式不关注你的匿名内部类的类名、也不关注方法名,它关注的是参数。即“让我们不用关注是什么对象。而是更关注我们对数据进行了什么操作。”

new Thread(()->{System.out.println("新线程中run方法被执行了");}).start();
  • 例二

现有方法定义如下,其中IntBinaryOperator是一个接口。先试用匿名内部类的写法调用该方法。

public static int calculateNum(IntBinaryOperator operator){
        int a= 10;
        int b= 20;
        return operator.applyAsInt(a, b);
    }

public static void main(string[] args){
    int i = calculateNum(new IntBinaryOperator() {
            @Override
            public int applyAsInt(int left, int right) {
                return left + right;
            }
        });
        System.out.println(i);
    }

使用Lambda表达式简化后的样子:

public static void test2_lambda(){
        int i = calculateNum((int left, int right)-> {````````````````````                return left + right;
            }
        );
        System.out.println("lambda:"+i);
    }

  • 例三:

现有方法定义如下,其中Intpredicate是一个接口。先使用匿名内部类的写法调用该方法。

 public static  void printNum(IntPredicate predicate){
        int[] arr = {1,2,3,4,5,6,7,8,9,10};
        for(int i : arr){
            if(predicate.test(i)){
                System.out.println(i);
            }
        }
    }
public static  void test3(){
        printNum(new IntPredicate() {
            @Override
            public boolean test(int value) {
                return value%2==0;
            }
        });
    }

lambda表达式的方式:

 public static  void test3_lambda(){
        printNum((int value)-> {
                return value%2==0;
            }
        );
    }

  • 例四:

现有方法定义如下,其中Function是一个接口。先使用匿名内部类的写法调用该方法。

public static <R> R typeconver (Function<String,R> function){
        String str = "1235";
        R result = function.apply(str);
        return result;
    }
 public static void test4(){
        Integer typeconver = typeconver(new Function<String, Integer>() {
            @Override
            public Integer apply(String s) {
                return Integer.valueOf(s);
            }
        });
        System.out.println("test4:"+typeconver);
    }

Lambda写法

 public static void test4_lambda(){
        Integer typeconver = typeconver((String s)-> {
            return Integer.valueOf(s);
        });
        System.out.println("test4_lambda:"+typeconver);
    }
  • 例五:

现有方法定义如下,其中IntConsumer是一个接口。先使用匿名内部类的写法调用该方法。

 public static void foreachArr(IntConsumer consumer) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        for (int i : arr) {
            consumer.accept(i);
        }
    }

public static  void test5(){
        foreachArr(new IntConsumer() {
            @Override
            public void accept(int value) {
                System.out.println("test5:"+value);
            }
        });
    }

lambda表达式

  public static  void test5_lambda(){
        foreachArr((int value)-> {
            System.out.println("test5:"+value);
        });
    }

2.4 省略规则

  • 参数类型可以省略
  • 方法体只有一句代码时大括号return和唯一—句代码的分号可以省略
  • 方法只有一个参数时小括号可以省略
  • 以上这些规则都记不住也可以省略不记

3、Stream流

3.1 概述

Java8的Stream使用的是函数式编程模式,如同它的名字一样,它可以被用来对集合或数组进行链状流式的操作。可以更方便的让我们对集合或数组操作。

3.2 案例数据准备

<dependencies>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.24</version>
    </dependency>
</dependencies>
@Data//(新版本Data已经包含@EqualsAndHashCode)
@NoArgsConstructor
@AllArgsConstructor
//@EqualsAndHashCode//用于后期的去重使用
public class Author {
    //id
    private Long id;
    //姓名
    private String name;
    //年龄
    private Integer age;
    //简介
    private String intro;
    //作品
    private List<Book> books ;
}

@Data//(新版本Data已经包含@EqualsAndHashCode)
@AllArgsConstructor
@NoArgsConstructor
//@EqualsAndHashCode //用于后期的去重使用
public class Book {
    //id
    private Long id;
    //书名
    private String name ;
    //分类
    private String category;
    //评分
    private Integer score;
    //简介
    private String intro;
}
public class StreamDemo {
    public static void main(String[] args) {
        List<Author> authors = getAuthors();
        System.out.println(authors);
    }
    private static List<Author> getAuthors(){
        //数据初始化
        Author author = new Author ( 1L,"蒙多", 33, "一个从菜刀中明悟哲理的祖安人", null);
        Author author2 = new Author( 2L,"亚拉索", 15,"狂风也追逐不上:他的思考速度",null);
        Author author3 = new Author( 3L,"易",14,"是这个世界在限制他的思维", null);
        Author author4 = new Author( 3L,"易", 14,"是这个世界在限制他的思维",null);

        List<Book> books1 = new ArrayList<>();
        List<Book> books2 = new ArrayList<>();
        List<Book> books3 = new ArrayList<>();

        books1.add(new Book(1L, "刀的两侧是光明与黑暗", "哲学,爱情" ,88, "用一把刀划分了爱恨"));
        books1.add(new Book(2L,"一个人不能死在同一把刀下","个人成长,爱情" ,99, "讲述如何从失败中明悟真理"));
        books2.add(new Book(3L, "那风吹不到的地方" ,"哲学",85, "带你用思维去领略世界的尽头"));
        books2.add(new Book(3L,"那风吹不到的地方", "哲学",85, "带你用思维去领略世界的尽头"));
        books2.add(new Book(4L , "吹或不吹" ,"爱情,个人传记" ,56,"一个哲学家的恋爱观注定很难把他所在的时代理解"));
        books3.add(new Book(5L , "你的剑就是我的剑", "爱情",56,"无法想象一个武者能对他的伴侣这么的宽容"));
        books3.add(new Book(6L, "风与剑" ,"个人传记",100,"两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));
        books3.add(new Book(6L,"风与剑","个人传记" ,100,"两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢?"));

        author.setBooks(books1);
        author2.setBooks (books2);
        author3.setBooks (books3);
        author4.setBooks(books3);

        List<Author> authorList = new ArrayList<>(Arrays.asList(author,author2,author3,author4));
        return authorList;
    }
}

3.3 快速入门

3.3.1 需求

我们可以调用getAuthors方法获取到作家的集合。现在需要打印所有年龄小于18的作家的名字,并且要注意去重。

3.3.2 实现

  • 匿名内部类的形式
 public static void main(String[] args) {
        List<Author> authors = getAuthors();
//        打印所有年龄小于18的作家的名字,并且要注意去重。
        authors.stream()//把集合转换成stream流
                .distinct()//先去除重复的作家
                .filter(new Predicate<Author>() {//筛选年龄小于18的
                    @Override
                    public boolean test(Author author) {
                        return author.getAge()<18;
                    }
                })//
                .forEach(new Consumer<Author>() {//遍历打印名称
                    @Override
                    public void accept(Author author) {
                        System.out.println("年龄小于18的作家的名字:"+author.getName());
                    }
                });
    }
  • lambda表达式的形式
public static void main(String[] args) {
        List<Author> authors = getAuthors();
        // 打印所有年龄小于18的作家的名字,并且要注意去重。
         authors.stream()//把集合转换成stream流
                .distinct()//先去除重复的作家
                .filter(author -> author.getAge()<18) //筛选年龄小于18的
                .forEach(author -> System.out.println("年龄小于18的作家的名字:"+author.getName()));//遍历打印名称
    }

3.4 常规操作

3.4.1 创建流

  • 单列结合:集合对象.stream()
List<Author> authors = getAuthors();
Stream<Author> stream = authors.stream();
  • 数组:Arrays.stream(数组)或者使用Stream.of(数组)来创建
Integer[] arr = {1,2,3,4,5};
Stream<Integer> stream = Arrays.stream(arr);
Stream<Integer> stream2= Stream.of(arr);
  • 双列集合:转换成单列集合后再创建
Map<String,Integer> map = new HashMap<>();
map.put("蜡笔小新",19);
map.put("黑子",17);
map.put("日向翔阳",16);
//使用entrySet()方法将map集合->set集合
Stream<Map.Entry<String,Integer>> stream = map.entrySet().stream();
Set<Map.Entry<String, Integer>>entrySet = map.entrySet();
Stream<Map.Entry<String, Integer>>stream = entrySet.stream()
stream.filter(new Predicate<Map.Entry<String, Integer>>(){
	@0verride
	public boolean test(Map.Entry<String, Integer> entry){
        return entry.getValue()>16;
    }
}).forEach (new Consumer<Map.Entry<String, IntegerÃsóÃ 

3.4.2 中间操作

3.4.2.1 filter(过滤)

  • 可以对流中的元素进行条件过滤,符合过滤条件的才能继续留在流中。
  • 例如:打印所有姓名长度大于1的作家的姓名
List<Author> authors = getAuthors();
authors.stream()
		.filter(author -> author.getName().length()>1)
		.forEach(author -> System.out.println(author.getName()))

3.4.2.2 map(计算或转换)

  • 可以把对流中的元素进行计算或转换。(map可以调用多次:比如我先转换再计算,把对象转换成年龄,在计算年龄)
  • 例如:打印所有作家的姓名
 //(1)利用forEach直接打印
authors.stream()
       .forEach(author -> System.out.println(author.getName()));
 //(2)利用map转换类型后再打印
//lambda表达式
authors.stream()
                .map(author -> author.getName())
                .forEach(s -> System.out.println(s));
//匿名类的方式
authors.stream()
                .map(new Function<Author, String>() {
                    @Override
                    public String apply(Author author) {
                        return author.getName();
                    }
                })
                .forEach(new Consumer<String>() {
                    @Override
                    public void accept(String s) {
                        System.out.println(s);
                    }
                });
  • 例如:将所有作家用map转换成年龄后,再将年龄+10,并打印出来
//lambda的方式 
authors.stream()
                .map(author -> author.getAge())
                .map(age -> age+10)
                .forEach(age -> System.out.println(age));
//匿名类的方式
 authors.stream()
                .map(new Function<Author, Integer>() {
                    @Override
                    public Integer apply(Author author) {
                        return author.getAge();
                    }
                })
                .map(new Function<Integer, Integer>() {
                    @Override
                    public Integer apply(Integer age) {
                        return age + 10;
                    }
                })
                .forEach(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer age) {
                        System.out.println(age);
                    }
                });

3.4.2.3 distinct(去重)

  • 可以去除流中的重复元素。
  • 例如:打印所有作家的姓名,并且要求其中不能有重复元素
 authors.stream()
        .distinct()
        .forEach(author -> System.out.println(author.getName()));

注意:distinct方法是依赖Object的equals方法来判断是否是相同对象的。所以需要注意重新equals方法。(lombok注解@Data中已经包含重写)

3.4.2.4 sorted

  • 可以对流中的元素进行排序
  • 例如:对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素
//(1)sorted()使用无参的方式,比较的对象的实体类(Author)需要实现Comparable接口
//public class Author implements Comparable<Author>{}
authors.stream()
    .distinct()
    .sorted()
    .forEach(author -> System.out.println(author));
//(2)sorted()使用有参的方式
authors.stream()
    .distinct()
    .sorted((o1, o2) -> o2.getAge()-o1.getAge())
    .forEach(author -> System.out.println(author));
  • 注意:如果调用空参的sorted()方法,需要流中的元素是实现了comparable接口。

3.4.2.5 limit

  • 可以设置流的最大长度,超出的部分将被抛弃

  • 例如:对流中的元素按照年龄进行降序排序,并且要求不能有重复的元素,然后打印出年龄最大的两个作家的姓名。

authors.stream()
    .distinct()
    .sorted((o1, o2) -> o2.getAge()-o1.getAge())
    .limit(2)
    .forEach(author -> System.out.println(author.getName()));

3.4.2.6 skip

  • 跳过流中的前n个元素,返回剩下的元素
  • 例如:打印除了年龄最大的作家外的其他作家,要求不能有重复元素,并且按照年龄降序排序。
authors.stream()
    .distinct()
    .sorted((a1,a2)->a2.getAge()-a1.getAge())
    .skip(1)
    .forEach(author -> System.out.println(author.getName()));

3.4.2.7 flatMap

  • map只能把一个对象转换成另一个对象来作为流中的元素。
  • 而flatMap可以把一个对象转换成多个对象作为流中的元素。
  • 例一:打印所有书籍的名字。要求对重复的元素进行去重
  //作者实体类中包含List<Book> books作品集合。flatMap的作用就是将一个authors.stream()转换成多个books.stream()的形式。
authors.stream()
      .flatMap(new Function<Author, Stream<Book>>() {
          @Override
          public Stream<Book> apply(Author author) {
              return author.getBooks().stream();
          }
      })
      .distinct()
      .forEach(book -> System.out.println(book.getName()));
  • 例二:打印现有数据的所有分类。要求对分类进行去重。(不能出现这种格式:哲学,爱情)

authors.stream()
    .flatMap(author -> author.getBooks().stream())  
    .distinct()
    .flatMap(book -> Arrays.stream(book.getCategory().split(",")))
    .distinct()
    .forEach(category -> System.out.println(category));

3.4.3 终结操作

3.4.3.1 forEach

  • 对流中的元素进行遍历操作,我们通过传入的参数去指定对遍历到的元素进行什么具体操作。
  • 例子:输出所有作家的名字
 authors.stream()
     .map(author -> author.getName())
     .distinct()
     .forEach(name -> System.out.println(name));

3.4.3.2 count

  • 可以用来获取当前流中元素的个数。
  • 例子:打印这些作家的所出书籍的数目,注意删除重复元素。
long count = authors.stream()
    .flatMap(author -> author.getBooks().stream())
    .distinct()
    .count();
System.out.println("这些作家的所出书籍的数目为:"+count);

3.4.3.3 max&min

  • 可以用来获取流中的最值
  • 例子:分别获取这些作家的所出书籍的最高分和最低分并打印
Optional<Integer> max = authors.stream()
    .flatMap(author -> author.getBooks().stream())
    .map(book -> book.getScore())
    .max((score1, score2) -> score1 - score2);
System.out.println("最高分:"+max.get());
Optional<Integer> min = authors.stream()
    .flatMap(author -> author.getBooks().stream())
    .map(book -> book.getScore())
    .min((score1, score2) -> score1 - score2);
System.out.println("最低分:"+min.get());

3.4.3.4 collect

  • 把当前流转化为一个集合。
  • 例子1:获取一个存放所有作者名字的List集合
List<String> nameList = authors.stream()
    .map(author -> author.getName())
    .collect(Collectors.toList());
System.out.println(nameList) ;
  • 例子2:获取一个所有书名的Set集合
Set<String> bookNameList = authors.stream()
    .flatMap(author -> author.getBooks().stream())
    .map(book -> book.getName())
    .collect(Collectors.toSet());
System.out.println(bookNameList);
  • 例子3:获取一个map集合,map的key为作者名,value为List
Map<String, List<Book>> authorMap = authors.stream()
    .distinct()
    .collect(Collectors.toMap(author -> author.getName(), 
                              author -> author.getBooks()));
System.out.println(authorMap);

关于Collectors.toMap()参数有三个的情况

详细信息请查看java 8 lamda Stream的Collectors.toMap 参数

使用toMap()函数之后,返回的就是一个Map了,自然会需要key和value。
toMap()的第一个参数就是用来生成key值的,

第二个参数就是用来生成value值的。

第三个参数用在key值冲突的情况下:如果新元素产生的key在Map中已经出现过了,第三个参数就会定义解决的办法。

3.4.3.5 查找与匹配

3.4.3.5.1 anyMatch
  • 可以用来判断是否有任意符合匹配条件的元素,结果为boolean类型。
  • 例子:判断是否有年龄在29以上的作家
boolean b = authors.stream()
    .anyMatch(author -> author.getAge() > 29);
System.out.println(b);
3.4.3.5.2 allMatch
  • 可以用来判断是否都符合匹配条件,结果为boolean类型。如果都符合结果为true,否则结果为false。
  • 例子:判断是否所有的作家都是成年人
boolean b = authors.stream()
    .allMatch(author -> author.getAge() >= 18);
System.out.println(b);
3.4.3.5.3 noneMatch
  • 可以判断流中的元素是否都不符合匹配条件。如果都不符合结果为true,否则结果为false。
  • 例子:判断作家是否都没有超过100岁
boolean b = authors.stream()
		.noneMatch(author -> author.getAge() > 100);
System.out.println(b);
3.4.3.5.4 findAny
  • 获取流中的任意一个元素。该方法没有办法保证获取的一定是流中的第一个元素。
  • 例子:获取任意一个年龄大于18的作家,如果存在就输出他的名字
Optional<Author> optionalAuthor = authors.stream()
    .filter(author -> author.getAge() > 18)
    .findAny();
optionalAuthor.ifPresent(author -> 		         	                             System.out.println(author.getName()));
3.4.3.5.5 findFirst
  • 获取流中的第一个元素。
  • 例子:获取一个年龄最小的作家,并输出他的姓名。
 Optional<Author> first = authors.stream()
                .sorted((author1, author2) -> author1.getAge() - author2.getAge())
                .findFirst();
first.ifPresent(author -> System.out.println(author.getName()));

3.4.3.6 reduce归并

  • 对流中的数据按照你指定的计算方式计算出一个结果。(缩减操作)
  • reduce的作用是把stream中的元素给组合起来,我们可以传入一个初始值,它会按照我们的计算方式依次的拿流中的元素和初始化值进行计算,计算结果再和后面的元素计算。
3.4.3.6.1 reduce俩个参数的重载形式
  • reduce俩个参数的重载形式内部的计算方式如下:
T result = identity;
for(T element : this stream)
	result = accumulator.apply(result,element)
return result;
int[]arr = {1,2,3,4,5}:
int sum = 0;
for (int i : arr){
    Sum= sum+i;
}
System. out. print(sum)
int[] arr = {1,2,3,4, 5};
int resut = l;
for (int i : arr){
    resut = resut*i;
}
System.out.print(resut)
  • 其中identity就是我们可以通过方法参数传入的初始值,accumulator的apply具体进行什么计算也是我们通过方法参数来确定的。
  • 例子1:使用reduce求所有作者年龄的和
//匿名内部类的方式
Integer result = authors.stream()
    .distinct()
    .map(author -> author.getAge())
    .reduce(0, new BinaryOperator<Integer>() {
        @Override
        public Integer apply(Integer result, Integer element) {
            return result + element;
        }
    });
System.out.println(result);
//lambda表达式
Integer result = authors.stream()
    .distinct()
    .map(author -> author.getAge())
    .reduce(0, (result1, element) -> result1 + element);
System.out.println(result);
  • 例子2:使用reduce求所有作者中年龄的最大值。
//注:求最大值,那么我们的初始化值就要是Integer.MIN_VALUE最小值。
Integer reduce = authors.stream()
    .map(author -> author.getAge())
    .reduce(Integer.MIN_VALUE, 
         (result, element) -> result > element ? result : element);
System.out.println(reduce);
  • 例子3:使用reduce求所有作者中年龄的最小值。
//注:求最小值,那么我们的初始化值就要是Integer.MAX_VALUE最大值。
Integer reduce = authors.stream()
    .map(author -> author.getAge())
    .reduce(Integer.MAX_VALUE,
         (result, element) -> result > element ? element : result);
System.out.println(reduce);
3.4.3.6.2 reduce一个参数的重载形式
  • reduce一个参数的重载形式内部的计算方式如下:****
boolean foundAny = false;
T result = null;
for (T element : this stream) {
    if (!foundAny) {
        foundAny = true;
        result = element;
    }
    else
        result = accumulator.apply(result, element);
}
return foundAny ? Optional.of(result) : Optional.empty();
  • 例子:如果用一个参数的重载方法形式求所有作者中年龄的最大值。
Optional<Integer> reduce = authors.stream()
    .map(author -> author.getAge())
    .reduce((result, element) -> result>element?result:element);
reduce.ifPresent(age -> System.out.println(age));

3.5 注意事项

  • 惰性求值(如果没有终结操作,没有中间操作是不会得到执行的)
  • 流是一次性的(一旦一个流对象经过一个终结操作后。这个流就不能再被使用)
  • 不会影响原数据(我们在流中可以多数据做很多处理。但是正常情况下是不会影响原来集合中的元素的。这往往也是我们所期望的)

4、Optional

4.1 概述

4.1.1 简介

  • 我们在编写代码的时候出现最多的就是空指针异常。所以在很多情况下我们需要做各种非空的判断。

例如:

Author author = getAuthor();
if(author != null){
    System.out.println(author.getName());
}
  • 尤其是对象中的属性还是一个对象的情况下。这种判断会更多。
  • 而过多的判断语句会让我们的代码显得臃肿不堪。
  • 所以在JDK8中引入了optional,养成使用Optional的习惯后你可以写出更优雅的代码来避免空指针异常。
  • 并且在很多函数式编程相关的API中也都用到了Optional,如果不会使用Optional也会对函数式编程的学习造成影响。

4.1.2 举例

4.1.2.1 出现空指针异常的列子

编码:

 List<Author> objects = new ArrayList<>();
        objects= null;
        objects.stream().forEach(new Consumer<Author>() {
            @Override
            public void accept(Author author) {
                System.out.println(author);
            }
        });

结果:

4.1.2.2 安全消费值(解决方法1)

编码:

//Lambda表达式:
Optional.ofNullable(objects)
                .ifPresent(authors -> authors.stream().forEach(author -> System.out.println(author)));
//匿名内部类
 Optional.ofNullable(objects)
                .ifPresent(new Consumer<List<Author>>() {
                    @Override
                    public void accept(List<Author> authors) {
                        authors.stream().forEach(new Consumer<Author>() {
                            @Override
                            public void accept(Author author) {
                                System.out.println(author);
                            }
                        });
                    }
                });

描述:其实就是加一个Optional.ofNullable(objects).ifPresent() 不为空才会进入该方法,方法中可以继续写lambda表达式

4.1.2.3 安全获取值(解决方法2)

编码:

 Optional.ofNullable(objects)
                .orElseGet(() -> Collections.emptyList()).stream().forEach(author -> System.out.println(author));

描述:

  • 其实就添加了Optional.ofNullable(objects).orElseGet( () -> Collections.emptyList() )

  • .orElseGet()判断是否为空,为空就返回方法中定义的返回结果;不为空就是传的值本身,不为空该方法不生效

  • emptyList()

作用:返回一个空的List(使用前提是不会再对返回的list进行增加和删除操作);

好处:

  1. new ArrayList()创建时有初始大小,占用内存,emptyList()不用创建一个新的对象,可以减少内存开销;

  2. 方法返回一个emptyList()时,不会报空指针异常,如果直接返回Null,没有进行非空判断就会报空指针异常;

注意:此List与常用的List不同,它是Collections类里的静态内部类,在继承AbstractList后并没有实现add()、remove()等方法,所以返回的List不能进行增加和删除元素操作。
原文链接:https://blog.csdn.net/zhuzicc/article/details/106277658

4.2 使用

4.2.1创建对象

Optional就好像是包装类,可以把我们的具体数据封装Optional对象内部。然后我们去使用Optional中封装好的方法操作封装进去的数据就可以非常优雅的避免空指针异常。

(常用)我们一般使用Optional的静态方法ofNullable来把数据封装成一个Optional对象。无论传入的参数是否为null都不会出现问题。

Author author = getAuthor();
Optional<Author> authorOptional = Optional.ofNullable(author);
authorOptional.ifPresent(auyhor ->                           							 System.out.println(author.getName()));
  • (常用)你可能会觉得还要加一行代码来封装数据比较麻烦。但是如果改造下getAuthor方法,让其的返回值就是封装好的Optional的话,我们在使用时就会方便很多。

  • 而且在实际开发中我们的数据很多是从数据库获取的。Mybatis从3.5版本可以也已经支持Optional了。我们可以直接把dao方法的返回值类型定义成Optional类型,MyBastis会自己把数据封装成Optional对象返回。封装的过程也不需要我们自己操作。

  • 如果你确定一个对象不是空的则可以使用Optional的静态方法of来把数据封装成Optional对象。

Author author = new Author();
Optional<Author> authorOptional = Optional.of(author);

但是一定要注意,如果使用of的时候传入的参数必须不为null。(尝试下传入null会出现什么结果)

如果一个方法的返回值类型是optional类型。而如果我们经判断发现某次计算得到的返回值为null,这个时候就需要把null封装成Optional对象返回。这时则可以使用Optional的静态方法empty来进行封装。

Optional.empty()

4.2.2 安全消费值

  • 我们获取到一个Optional对象后肯定需要对其中的数据进行使用。这时候我们可以使用其ifPresent方法对来消费其中的值。这个方法会判断其内封装的数据是否为空,不为空时才会执行具体的消费代码。这样使用起来就更加安全了。

  • 例如,以下写法就优雅的避免了空指针异常。

optiona1<Author> authoroptiona1 = optiona1.ofNu11able(getAuthor());
authoroptiona1.ifPresent(author -> 
                         system.out.printin(author .getName()));

4.2.3 获取值

  • 如果我们想获取值自己进行处理可以使用get方法获取,但是不推荐。因为当Optional内部的数据为空的时候会出现异常。

4.2.4 安全获取值

  • 如果我们期望安全的获取值。我们不推荐使用get方法,而是使用Optional提供的以下方法。
  • orElseGet
  • 获取数据并且设置数据为空时的默认值。如果数据不为空就能获取到该数据。如果为空则根据你传入的参数来创建对象作为默认值返回。
optiona1<Author> authoroptional = optiona1.ofNu11ab1e(getAuthor());
//无参
Author author1 = authoroptiona1.orE1seget(()-> new Author());
//有参,默认值为有参的参数
Author author1 = authoroptiona1.orE1seget(()-> new Author(作者对象));
  • orElseThrow
    • 获取数据,如果数据不为空就能获取到该数据。如果为空则根据你传入的参数来创建异常抛出。
optiona1<Author> 																authoroptional=optiona1.ofNu11able(getAuthor());
	try {
		Author author = 														authoroptiona1.orE1seThrow(
        			(Supp1ier<Throwab1e>)() ->												 new RuntimeException("author为空"));
			system.out.print1n(author.getName());
	}catch (Throwab1e throwab1e) {
		throwable.printstackTrace();
	}

4.2.5 过滤

  • 我们可以使用filter方法对数据进行过滤。如果原本是有数据的,但是不符合判断,也会变成一个无数据的optional对象
optiona1<Author> authoroptional = optiona1.ofNu11ab1e(getAuthor());
authoroptiona1.filter(author -> author. getAge()>100)
			.ifPresent(author ->
						system. out.print1n(author. getName()));

4.2.6 判断

  • 我们可以使用isPresent方法进行是否存在数据的判断。如果为空返回值为false,如果不为空,返回值为true。但是这种方式并不能体现optional的好处,更推荐使用ifPresent方法。
optiona1<Author> authoroptiona1 = optiona1.ofNu11ab1e(getAuthor());
		if (authoroptional .isPresent()) {
			system.out.print1n(authoroptiona1.get().getName());
		}

4.2.7 数据转换

  • Optional还提供了map可以让我们的对数据进行转换,并且转换得到的数据也还是被Optional包装好的,保证了我们的使用安全。
  • 例如:我们想获取作家的书籍集合。
private static void testMap(){
	optional<Author> authoroptional = getAuthoroptional();
    Optional<List<Book>> optionalBooks = authoroptional.map(author -> author .getBooks());
    optionalBooks.ifPresent(books >system.out.printin(books));
optional<Author> authoroptional = optional.ofNu11able(getAuthor());
optional<List<Book>> books = 
    		authoroptional.map(author -> author. getBooks());
books.ifPresent(new Consumer<List<Book>>(){
        public void accept(List<Book> books){
        books.forEach(book -> system.out.print1n(book.getName()));
		}
	});

5、函数式接口

5.1 概述

  • 只有一个抽象方法的接口我们称之为函数接口。
  • JDK的函数式接口都加上了@Functionallnterface注解进行标识。但是无论是否加上该注解只要接口中只有一个抽象方法,都是函数式接口。

5.2 常见的函数式接口

  • Consumer消费接口
    • 根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数进行消费。

Function计算转换接口

  • 根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数计算或转换,把结果返回

Predicate判断接口

  • 根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中对传入的参数条件判断,返回判断结果

Supplier生产型接口

  • 根据其中抽象方法的参数列表和返回值类型知道,我们可以在方法中创建对象,把创建好的对象返回

5.3 常用的默认方法

  • and
    • 我们在使用Predicate接口时候可能需要进行判断条件的拼接。而and方法相当于是使用&&来拼接两个判断条件例如:
    • 例如:打印作家中年龄大于17并且姓名的长度大于1的作家。
List<Author> authors = getAuthors();
Stream<Author> authorstream = authors.stream();
authorstream.filter(new Predicate<Author>(){
    @override
    public boolean test(Author author){
        return author.getAge()>17;
}.and(new Predicate<Author>(){
        @override
        public boolean test(Author author){
            return author.getName().length()>1;
})).forEach(author -> system.out.printin(author));

or

  • 我们在使用Predicate接口时候可能需要进行判断条件的拼接。而or方法相当于是使用||来拼接两个判断条件。例如:
  • 例如:打印作家中年龄大于17或者姓名的长度小于2的作家。
打印作家中年龄大于17或者姓名的长度小于2的作家
List<Author>authors= getAuthors();
authors.stream()
    .filter(new Predicate<Author>(){
        @0verride
        public boolean test(Author author){
            return author.getAge()>17:
        }
    }.or(new Predicate<Author>(){
        @0verride
        public boolean test(Author author){
            return author. getName ().length()<2:
        }
})).forEach (author ->System. out. println(author.getName())):

negate

  • Predicate接口中的方法。negate方法相当于是在判断添加前面加了个!表示取反
  • 例如:打印作家中年龄不大于17的作家。
打印作家中年龄不大于17的作家。
List<Author>authors= getAuthors();
authors.stream()
    .filter(new Predicate<Author>(){
        @Override
        public boolean test(Author author){
            return author.getAge()>17:
        }
    }.negate()).forEach(author ->System. out. println(author.getAge()));

6、方法引用、

我们在使用lambda时,如果方法体中只有一个方法的调用的话(包括构造方法) ,我们可以用方法引用进一步简化代码。

6.1 推荐用法

我们在使用lambda时不需要考虑什么时候用方法引用,用哪种方法引用,方法引用的格式是什么。我们只需要在写完lambda方法发现方法体只有一行代码,并且是方法的调用时使用快捷键尝试是否能够转换成方法引用即可。

  • 当我们方法引用使用的多了慢慢的也可以直接写出方法引用。

6.2从基本格式

类名或者对象名::方法名

6.3 语法详解(了解)

6.3.1 引用类的静态方法

  • 其实就是引用类的静态方法

  • 格式

    • 类名::方法名
      
  • 使用前提

    • 如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个类的静态方法,并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个静态方法中,这个时候我们就可以引用类的静态方法。
  • 例如:如下代码就可以用方法引用进行简化

List<Author> authors = getAuthors();
Stream<Author> authorstream = authors.stream();
authorstream.map(author ->author.getAge()).map(age->string.valueof(age));

  • 注意:如果我们所重写的方法是没有参数的,调用的方法也是没有参数的也相当于符合以上规则。
  • 优化后如下:
List<Author> authors = getAuthors();
Stream<Author> authorstream = authors.stream()
authorstream.map(author -> author.getAge()).map(string::valueof);

6.3.2 引用对象的实例方法格式

  • 格式
对象名::方法名
  • 使用前提
    • 如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个对象的成员方法,并且我们把要重写的抽象方法中所有的参数都按照顺序传入了这个成员方法中,这个时候我们就可以引用对象的实例方法
  • 例如:
    • 优化前:
List<Author> authors = getAuthors();

Stream<Author> authorstream = authors.stream();
StringBuilder sb = new stringBuilder();
authorstream.map(author -> author.getName())
    .forEach(name->sb.append(name));

优化后:

List<Author> authors =getAuthors();

Stream<Author> authorstream= authors.stream();
StringBuilder sb = new stringBuilder();
authorstream.map(author -> author.getName())
    .forEach(sb::append);CSDN 

6.3.3 引用类的实例方法

  • 格式
类名::方法名
  • 使用前提
    • 如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了第一个参数的成员方法,并且我们把要重写的抽象方法中剩余的所有的参数都按照顺序传入了这个成员方法中,这个时候我们就可以引用类的实例方法。
  • 例如:
    • 优化前

优化后

6.3.4 构造器引用

如果方法体中的一行代码是构造器的话就可以使用构造器引用。

  • 格式
类名::new
  • 使用前提
    • 如果我们在重写方法的时候,方法体中只有一行代码,并且这行代码是调用了某个类的构造方法,并且我们把要重写的抽象方法中的所有的参数都按照顺序传入了这个构造方法中,这个时候我们就可以引用构造器。
  • 例如:
    • 优化前
List<Author> authors = getAuthors();
authors .stream()
    .map(author -> author.getName())
    .map(name->new stringBuilder(name))
    .map(sb->sb.append("-三更").tostring())
    .forEach(str-> system.out.printin(sra);

优化后

List<Author> authors = getAuthors();
authors .stream()
    .map(author ->author.getName())
    .map(stringBuilder::new)
    .map(sb->sb.append("-三更").tostring())
    .forEach(str-> system.out.printin(str));

7、高级用法

7.1 基本数据类型优化

  • 我们之前用到的很多Stream的方法由于都使用了泛型。所以涉及到的参数和返回值都是引用数据类型。
  • 即使我们操作的是整数小数,但是实际用的都是他们的包装类。JDK5中引入的自动装箱和自动拆箱让我们在使用对应的包装类时就好像使用基本数据类型一样方便。但是你一定要知道装箱和拆箱肯定是要消耗时间的。虽然这个时间消耗很下。但是在大量的数据不断的重复装箱拆箱的时候,你就不能无视这个时间损耗了。
  • 所以为了让我们能够对这部分的时间消耗进行优化。Stream还提供了很多专门针对基本数据类型的方法。
  • 例如: mapTolnt、mapToLong、mapToDouble、flatMapTolnt、flatMapToDouble等。

7.2 并行流

  • 当流中有大量元素时,我们可以使用并行流去提高操作的效率。其实并行流就是把任务分配给多个线程去完全。如果我们自己去用代码实现的话其实会非常的复杂,并且要求你对并发编程有足够的理解和认识。而如果我们使用Stream的话,我们只需要修改一个方法的调用就可以使用并行流来帮我们实现,从而提高效率。

  • parallel方法可以把串行流转换成并行流。

也可以通过parallelStream直接获取并行流对象。

例如:

  • 优化前:串行的方式

优化后:调用parallel()方法即可实现并行流

7.3 peek()可以作为开发者测试使用

使用peek()可以测试查看当前流中的运行情况。例如:下图就是利用peek观察并行流的线程使用情况。

7.4 串行流与并行流的举例

public class Parallel {
    public static void main(String[] args) {
        int num[] = new int[]{1,2,3,4};
        System.out.println("并行——————————");
        Arrays.stream(num).parallel()
                .peek(value -> System.out.println(value+Thread.currentThread().getName()))
                .forEach(value -> System.out.println(value));
        System.out.println("串行——————————");
        Arrays.stream(num)
                .peek(value -> System.out.println(value+Thread.currentThread().getName()))
                .forEach(value -> System.out.println(value));
    }
}

7.5 串行流与并行流的优劣

串行流与并行流之间的效率差异取决于多种因素,包括数据大小、处理器核心数、任务的并行性以及是否存在数据竞争。在Java 8及之后的版本中,parallelStream() 提供了并行处理数据的能力,但这并不意味着在所有情况下它都比普通的 stream() 更快。
以下是一些关键点,需要考虑它们来评估 parallelStream() 的效率:
● 数据大小:对于小数据集,parallelStream() 可能不会带来明显的性能提升,因为并行处理需要拆分任务、分配线程以及合并结果,这些操作可能会带来额外的开销。然而,对于大数据集,parallelStream() 可以充分利用多核处理器,从而提高性能。
● 任务的并行性:parallelStream() 的效率还取决于任务的并行性。如果任务不是高度并行的,即任务之间存在数据竞争或依赖关系,那么并行处理可能不会带来预期的性能提升。在这种情况下,普通的 stream() 可能会更高效。
● 处理器核心数:并行流的性能还受到可用处理器核心数的影响。如果处理器核心数较少,那么并行处理可能不会带来明显的性能提升。在这种情况下,使用 parallelStream() 可能会导致线程间的竞争,从而降低性能。
● 数据竞争:如果并行操作中存在数据竞争,那么需要使用适当的同步机制来确保数据的正确性。这可能会导致额外的性能开销。
为了确定 parallelStream() 是否比普通的 stream() 更高效,建议进行基准测试,比较不同数据集大小、不同处理器核心数以及不同任务并行性下的性能。在实际应用中,需要根据具体情况选择使用 parallelStream() 还是普通的 stream()。
总之,list.stream().parallel() 在某些情况下可能会提高性能,但这取决于多种因素。在决定使用 parallelStream() 之前,请务必评估您的应用场景和需求。

8、扩展

8.1 Java中的IntStream range()方法的使用

 /**
     * Returns a sequential ordered {@code IntStream} from {@code startInclusive}
     * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of
     * {@code 1}.
     *
     * @apiNote
     * <p>An equivalent sequence of increasing values can be produced
     * sequentially using a {@code for} loop as follows:
     * <pre>{@code
     *     for (int i = startInclusive; i < endExclusive ; i++) { ... }
     * }</pre>
     *
     * @param startInclusive the (inclusive) initial value
     * @param endExclusive the exclusive upper bound
     * @return a sequential {@code IntStream} for the range of {@code int}
     *         elements
     */
    public static IntStream range(int startInclusive, int endExclusive) {
        if (startInclusive >= endExclusive) {
            return empty();
        } else {
            return StreamSupport.intStream(
                    new Streams.RangeIntSpliterator(startInclusive, endExclusive, false), false);
        }
    }

说明:

  • range()方法,创建一个以1为增量步长,从startInclusive(包括)到endExclusive(不包括)的有序的数字流。
  • 产生的IntStream对象,可以像数组一样遍历。****
static IntStream range(int startInclusive,int endExclusive);

参数:

IntStream : 原始整数值元素的序列
startInclusive : 规定了数字的起始值,包括
endExclusive : 规定了数字的上限值,不包括

返回值

一个int元素范围的顺序IntStream

导包:

要使用Java中的IntStream类,请导入以下包:

import java.util.stream.IntStream;

举例:

class RangeTest {
    public static void main(String[] args) {
        /*
         * Creating an IntStream:
         *    --including the lower bound but
         *    --excluding the upper bound
         */
        IntStream intStream = IntStream.range(1,5);
 
        // Displaying the elements in range
        intStream.forEach(System.out::println);
 
        //上述代码简要写法
//      IntStream.range(1,5).forEach(i-> System.out.println(i));//创建一个1-4的数字流,并打印
    }
}

8.2 如果想要数字是闭区间,可以使用 rangeClosed() 方法

static IntStream rangeClosed(int startInclusive, int endInclusive)

此方法和range的使用一模一样,唯一的区别是endInclusive参数是包含的

8.3 使用Collectors.groupingBy()方法,实现对数据进行分组

  • Collectors.groupingBy()方法

Collectors.groupingBy()是一个非常有用的收集器,可以根据给定的分类函数对数据进行分组。该方法有两个重载版本,一个使用分类函数,另一个使用分类函数和一个提取结果函数。
在使用Collectors.groupingBy()时,需要提供一个分类函数,它将返回一个用于分组的键。例如,假设我们有一个名为Person的类,其中包含名字和年龄两个属性,我们可以按照年龄将Person对象分组,如下所示:

Map<Integer, List<Person>> peopleByAge = people.stream()     
.collect(Collectors.groupingBy(Person::getAge)); 

在上面的代码中,Person::getAge是一个分类函数,将返回每个Person对象的年龄作为分组键。该方法将返回一个Map<Integer, List>对象,其中分组键是年龄,对应的值是一个Person对象列表,其中每个Person对象都具有相同的年龄。

  • 多级分组

使用Collectors.groupingBy()方法,我们可以轻松地将数据按照单个分类器进行分组。但是,在某些情况下,我们可能需要在聚合过程中使用多个级别的分类器。例如,假设我们有一个包含Person对象的列表,我们想按性别和年龄对它们进行分组,如下所示:

Map<String, Map<Integer, List<Person>>> peopleByGenderAndAge = people.stream()     
.collect(Collectors.groupingBy(Person::getGender,              
Collectors.groupingBy(Person::getAge))); 

在上面的代码中,我们使用了两个分类函数,Person::getGender和Person::getAge,将Person对象按性别和年龄分组。该方法将返回一个Map<String, Map<Integer, List>>对象,其中外部Map的键是性别,内部Map的键是年龄,对应的值是具有相同性别和年龄的Person对象列表。

  • 使用提取函数进行分组

在某些情况下,我们需要使用分类函数生成分组键的一部分,而使用提取函数生成分组键的另一部分。例如,假设我们有一个名为Person的类,其中包含名字和年龄两个属性,我们想按照首字母和年龄对它们进行分组,如下所示:

Map<Character, Map<Integer, List<Person>>> peopleByFirstInitialAndAge = people.stream()     
.collect(Collectors.groupingBy(person -> person.getName().charAt(0),              
Collectors.groupingBy(Person::getAge))); 

在上面的代码中,我们使用了两个函数来生成分组键。对于外部Map,我们使用了一个lambda表达式,以每个Person对象的名字的首字母作为键。对于内部Map,我们使用了Person::getAge作为分类函数,将Person对象按年龄分组。该方法将返回一个Map<Character, Map<Integer, List>>对象,其中外部Map的键是名字的首字母,内部Map的键是年龄,对应的值是具有相同首字母和年龄的Person对象列表。

  • 使用Collectors.counting()函数统计分组结果

在上面的例子中,我们将Person对象分组并存储在Map对象中,但是我们也可以使用其他收集器来聚合分组结果。例如,我们可以使用Collectors.counting()函数来计算每个分组中Person对象的数量,如下所示:

Map<String, Long> countByGender = people.stream()     
.collect(Collectors.groupingBy(Person::getGender, Collectors.counting())); 

在上面的代码中,我们使用Person::getGender作为分类函数,将Person对象按性别分组。我们还使用Collectors.counting()函数,计算每个分组中Person对象的数量,并将结果存储在一个Map<String, Long>对象中,其中键是性别,值是对应的Person对象数量。

举例:

// 单条件分组,
   Map<String, List<YourBean>> mapByOne = yourBeanList.stream().collect(Collectors.groupingBy(YourBean::getBillDateStr));

   // 分组后,统计每组中数据量
   Map<String, Long> count = yourBeanList.stream().collect(Collectors.groupingBy(YourBean::getBillDateStr, Collectors.counting()));

   // 分组后,求出每组中某属性的平均值
   Map<String, Double> avg = yourBeanList.stream().filter(i -> i.getGoodAmount() != null).
          collect(Collectors.groupingBy(YourBean::getBillDateStr, Collectors.averagingDouble(YourBean::getGoodAmount)));

   // 分组,某属性求和
   Map<String, Double> sum = yourBeanList.stream().filter(i -> i.getGoodAmount() != null).
                collect(Collectors.groupingBy(YourBean::getBillDateStr, Collectors.summingDouble(YourBean::getGoodAmount)));

        //对求和的结果集进行从大到小排序
   Map<String, Double> finalMap = new LinkedHashMap<>();
   sum.entrySet().stream().sorted(Map.Entry.<String, Double>comparingByValue().reversed()).forEachOrdered(e -> finalMap.put(e.getKey(), e.getValue()));

   // 分组后,通过join组成新的map
   Map<String, String> joinNewMap = yourBeanList.stream().filter(i -> i.getGoodAmount() != null)
                .collect(Collectors.groupingBy(YourBean::getBillDateStr,
                        Collectors.mapping(i -> i.getGoodAmount().toString(), Collectors.joining(", ", "Post titles: [", "]"))));
   // 2022-04-23
   // Post titles: [3.0, 1.0, 2.0, 3.0]
   // 转换分组结果List -> Set
   Map<String, Set<String>> namesByName = yourBeanList.stream()
                .collect(Collectors.groupingBy(YourBean::getBillDateStr, Collectors.mapping(YourBean::getGoodName, Collectors.toSet())));
   Set<String> x = namesByCity.keySet();

   // 两个条件分组
   Map<String, Map<String, List<YourBean>>> mapByTwo = yourBeanList.stream()
                .collect(Collectors.groupingBy(YourBean::getBillDateStr, Collectors.groupingBy(YourBean::getGoodName)));

俩个集合,一个分类集合A(dictionaryPoList),一个数据集合B(medUserArchivesPoList),数据集合B根据分类A进行分组,并计数。

/**
	 * 封装学历或职位分组和计数
	 * @param leaderResultList 初始化数据
	 * @param medUserArchivesPoList	用户数据
	 * @param dictionaryPoList	字典数据
	 * @param type	操作类型(学历、职称)
	 * @return
	 */
	private List<LeaderResultVo> packageGroupCount(List<LeaderResultVo> leaderResultList,List<MedUserArchivesPo> medUserArchivesPoList,
												   List<DictionaryPo> dictionaryPoList,String type){
		//实现分组和计数
		Map<String, Long> countMap = medUserArchivesPoList.stream()
				.collect(Collectors.groupingBy(user -> {
					for(DictionaryPo dictionaryPo:dictionaryPoList){
						if(type.equals(LeaderCockptConstant.EDUCATION_)){
							if(dictionaryPo.getKey().equals(user.getEducation())){
								return dictionaryPo.getName();
							}
						}
						if(type.equals(LeaderCockptConstant.POSITIONAL_)){
							if(dictionaryPo.getKey().equals(user.getPositional())){
								return dictionaryPo.getName();
							}
						}
					}
					return LeaderCockptConstant.OTHER;
				}, Collectors.counting()));
        
		countMap.forEach((edu, count) -> {
			for(LeaderResultVo resultVo:leaderResultList){
				if(edu.equals(resultVo.getName())){
					resultVo.setValue(Math.toIntExact(count));
				}
			}
		});
		return leaderResultList;
	}

标签:Stream,函数,stream,author,编程,System,authors,new,out
From: https://www.cnblogs.com/ReturnMa/p/18349895

相关文章

  • C语言学习笔记 Day8(函数)
    Day8 内容梳理:目录Chapter6 函数6.0概述6.1 定义函数6.2 调用函数(1)实参&形参(2)调用无参函数(3)调用有参函数6.3 声明函数6.4 终止函数(exit&return)6.5多文件编程(1)设置主文件(2)创建头文件(3)导入头文件Chapter6 函数6.0概述函数的分类(2种):   ......
  • 51单片机之模块化编程
    一、模块化编程与传统方式编程的区别传统方式编程:在这种编程方式中,所有的函数通常都被放置在同一个文件main.c中。当项目中使用的模块较多时,这个文件中会包含大量的代码,导致代码难以组织和管理,也影响了编程者的思路。这种方式缺乏清晰的结构划分,使得代码的可读性和可维护性降......
  • 教你领悟函数递归的本质
    一、何为递归①在C语言中,递归就是函数自己调用自己。递是指递推,归是指回归。②递归的思想:将复杂的问题简单化。③递推的两个必要条件。a:递归存在限制条件,当满足限制条件时,递归便不再继续b:每一次递归都要越来越接近限制条件/*用递归的方式求n!(n>=0)*/intFact(i......
  • FreeRTOS启动任务调度器函数解释
    目录vTaskStartScheduler()函数xPortStartScheduler()函数prvStartFirstTask()函数vPortSVCHandler()函数FreeRTOS的任务开始运行的前提是调用了启动调度器函数vTaskStartScheduler(),只有调用了该函数任务才会被调度并运行。下面以FreeRTOSv9.0.0版本的源码进行分析FreeRT......
  • C语言--函数
    函数的概述:函数:实现一定功能的,独立的代码模块。函数一定是先定义,后使用使用函数的优势:·我们可以通过函数提供功能给别人使用,也可以使用别人提供的函数,减少代码量               ·借助函数可以减少重复的代码               ·实现结构化(......
  • 轮换挑选图片,补充 es6的对象写法,uniapp使用,class和style,条件渲染,列表渲染,input
    Ⅰ轮换挑选图片【一】方式一<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title><scriptsrc="./js2/vue.js"></script></head><body>......
  • Java设计模式和AOP编程
    Java六大设计原则;Java23种设计模式(在此介绍三种设计模式)Java设计模式单例模式应用场景:spring中bean的作用域用的就是单例模式//基本的单例模式————懒汉式publicclassstudent{//3.创建static修饰的成员变量privatestaticstudentstu;//1.设计私......
  • 不需要学编程,自制自己的操作系统!一个0基础自制操作系统的软件!详细教程!
    不需要学编程,自制自己的操作系统!一个0基础自制操作系统的软件!详细教程创建.py文件,内容如下fromtkinterimport*code='\n[org0x7c00]\n\nstart:\n\t\n\tmovbp,0x8000\n\tmovsp,bp\n\n\t\n\tmovax,0x0600\n\tmovbx,0x0700\n\tmovcx,0\n\tmovdx,0x184f\n\tint......
  • CH2~CH5 DataStream API基础
    一个Flink程序,就是对DataStream进行各种转换。基本上由以下几部分构成接下来分别从执行环境、数据源、转换操作、输出四大部分,介绍DataStreamAPI。导入ScalaDataStreamApiimportorg.apache.flink.streaming.api.scala._CH-5DataStreamAPI基础一、执行环境1.1创建执......
  • 目录函数以及链接文件
    一、stat补充1、getpwuid()structpasswd*getpwuid(uid_tuid);功能:根据用户id到/etc/passwd文件下解析获得结构体信息参数:uid:用户id返回值:成功返回id对应用户的信息失败返回NULL2、getgrgid()structgroup*getgrgid(gid_tgid);拿到组的结构体功能:根据gid......