Java8 Stream流多字段求和、汇聚的实例

 更新时间:2022年05月06日 11:35:13   作者:我想写游戏  
这篇文章主要介绍了Java8 Stream流多字段求和、汇聚的实例,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

Stream流多字段求和、汇聚

实现方法

利用

Collectors.toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction)
  • keyMapper:代表你最终想要获得的Map<Key, Value> 的Key
  • valueMapper:代表你最终想要获得的Map<Key, Value> 的Value
  • mergeFunction:表示碰到Key冲突是处理过程,{x, y}中x是已汇聚对象,y表示当前处理对象

对象类型数据处理

public static Map<String, Model> streamGroupSum(List<Model> datas){
    return datas.stream().collect(Collectors.toMap(k -> k.getCode(), v -> v, (x, y) -> x.addCount().addAll(y)));
  }

Model

@Data
class Model{
    private String code;
    private int count = 0;
    private Integer sum1;
    private Integer sum2;
    public Model(String code, Integer sum1, Integer sum2){
      this.code = code;
      this.sum1 = sum1;
      this.sum2 = sum2;
    }
    public Model addCount(){
      this.count++;
      return this;
    }
    
    public Model addAll(Model y){
      return add(Model::setSum1, Model::getSum1, y)
          .add(Model::setSum2, Model::getSum2, y);
    }
    /**
    * 使用函数式编程,最终目的是为了求和,类似反射,具体使用方式请移步函数式编程
    */
    public Model add(BiConsumer<Model, Integer> set, Function<Model, Integer> get, Model y){
      set.accept(this, get.apply(this) + get.apply(y));
      return this;
    }
  }

Map类型数据处理

public static void main (String[] args) {
    List<Map<String, Object>> datas = getDatas();
    streamMapSum(datas);
  }
  public static Map<Object, Map<String, Object>> streamMapSum (List<Map<String, Object>> datas) {
    return datas.stream()
        .collect(Collectors.toMap(k -> k.get("name"), v -> {
              v.put("count", 1);
              return v;
            }
            , (x, y) -> {
             	x.put("count", (int) x.get("count") + 1);
             	x.put("aaa", (int) x.get("aaa") + (int) y.get("aaa"));
             	x.put("bbb", (int) x.get("bbb") + (int) y.get("bbb"));
             	x.put("ccc", (int) x.get("ccc") + (int) y.get("ccc"));
             	return x;
             	/*
              //使用ofMap重构
              return ofMap("name", x.get("name")
                  , "count", (int) x.get("count") + 1
                  , "aaa", add(x, y, "aaa")
                  , "bbb", add(x, y, "bbb")
                  , "ccc", add(x, y, "ccc"));*/
             }
         )
    );
              
  }
  public static int add (Map<String, Object> x, Map<String, Object> y, String key) {
    return (int) x.get(key) + (int) y.get(key);
  }
  public static Map<String, Object> ofMap (Object... objs) {
    System.out.println("ofMap");
    Map<String, Object> map = new LinkedHashMap<>();
    for (int i = 0; i < objs.length; i = i + 2) {
      map.put(objs[i].toString(), objs[i + 1]);
    }
    return map;
  }
  public static List<Map<String, Object>> getDatas () {
    List<Map<String, Object>> list = new ArrayList<>();
    list.add(ofMap("name", "张三", "aaa", 3, "bbb", 5, "ccc", 6));
    list.add(ofMap("name", "张三", "aaa", 8, "bbb", 51, "ccc", 521));
    list.add(ofMap("name", "李四", "aaa", 9, "bbb", 53, "ccc", 23));
    return list;
  }

Stream分组求和使用笔记

话不多说,直接贴代码,分组使用

class Foo {
    private int code;
    private int count;
    public Foo(int code, int count) {
        this.code = code;
        this.count = count;
    }
    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
    public int getCount() {
        return count;
    }
    public void setCount(int count) {
        this.count = count;
    }
}
public static void main(String[] args) {
        Foo foo1 = new Foo(1, 2);
        Foo foo2 = new Foo(2, 23);
        Foo foo3 = new Foo(2, 6);
        List<Foo> list = new ArrayList<>(4);
        list.add(foo1);
        list.add(foo2);
        list.add(foo3);
        Map<Integer, List<Foo>> collect = list.stream().collect(Collectors.groupingBy(Foo::getCode));
        List<Foo> list1 = collect.get(1);
        List<Foo> list2 = collect.get(2);
        list1.forEach(e -> System.out.println(e.getCode() + ":" + e.getCount()));
        System.out.println("-----------这里是分界线-----------------------------");
        list2.forEach(e -> System.out.println(e.getCode() + ":" + e.getCount()));
    }

输出结果:

1:2
-----------这里是分界线-----------------------------
2:23
2:6

分组求和使用

public static void main(String[] args) {
        Foo foo1 = new Foo(1, 2);
        Foo foo2 = new Foo(2, 23);
        Foo foo3 = new Foo(2, 6);
        List<Foo> list = new ArrayList<>(4);
        list.add(foo1);
        list.add(foo2);
        list.add(foo3);
        Map<Integer, IntSummaryStatistics> collect = list.stream().collect(Collectors.groupingBy(Foo::getCode, Collectors.summarizingInt(Foo::getCount)));
        IntSummaryStatistics statistics1 = collect.get(1);
        IntSummaryStatistics statistics2 = collect.get(2);
        System.out.println(statistics1.getSum());
        System.out.println(statistics1.getAverage());
        System.out.println(statistics1.getMax());
        System.out.println(statistics1.getMin());
        System.out.println(statistics1.getCount());
        System.out.println(statistics2.getSum());
        System.out.println(statistics2.getAverage());
        System.out.println(statistics2.getMax());
        System.out.println(statistics2.getMin());
        System.out.println(statistics2.getCount());
    }

输出结果:

2
2.0
2
2
1
29
14.5
23
6
2

stream真的是相当的好用,Mark一下,欢迎大神在评论区留下你的Stream骚操作。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 教你如何使用Java输出各种形状

    教你如何使用Java输出各种形状

    本文小编将向大家介绍的是如何利用Java输出各种不同的形状,本文一共介绍了七种有趣的形状,感兴趣的小伙伴赶快收藏起来吧
    2021-09-09
  • Java中Integer类型值相等判断方法

    Java中Integer类型值相等判断方法

    这篇文章主要给大家介绍了关于Java中Integer类型值相等判断的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-02-02
  • Java开发中的OOM内存溢出问题详解

    Java开发中的OOM内存溢出问题详解

    这篇文章主要介绍了Java开发中的OOM内存溢出问题详解,OOM,全称 Out Of Memory,意思是内存耗尽或内存溢出,当JVM因为没有足够的内存来为对象分配空间并且垃圾回收器也已经没有空间可回收时,就会抛出这个 error,需要的朋友可以参考下
    2023-08-08
  • Java中典型的内存泄露问题和解决方法

    Java中典型的内存泄露问题和解决方法

    这篇文章主要介绍了Java中典型的内存泄露问题和解决方法,典型的内存泄露例子是一个没有实现hasCode和 equals方法的Key类在HashMap中保存的情况,可以通过实现Key类的equals和hasCode方法解决这种内存泄漏问题,需要的朋友可以参考下
    2014-04-04
  • 在Java的Struts框架下进行web编程的入门教程

    在Java的Struts框架下进行web编程的入门教程

    这篇文章主要介绍了在Java的Struts框架下进行web编程的入门教程,需要的朋友可以参考下
    2015-11-11
  • SpringBoot启动时自动执行代码的几种实现方式

    SpringBoot启动时自动执行代码的几种实现方式

    这篇文章主要给大家介绍了关于SpringBoot启动时自动执行代码的几种实现方式,文中通过实例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2022-02-02
  • Springboot使用RabbitMQ实现关闭超时订单(示例详解)

    Springboot使用RabbitMQ实现关闭超时订单(示例详解)

    介绍了如何在Spring Boot项目中使用RabbitMQ实现订单的延时处理和超时关闭,通过配置RabbitMQ的交换机、队列和绑定关系,以及编写监听方法,实现了订单数据的发送和延时消费,感兴趣的朋友一起看看吧
    2025-01-01
  • 基于SpringBoot 使用 Flink 收发Kafka消息的示例详解

    基于SpringBoot 使用 Flink 收发Kafka消息的示例详解

    这篇文章主要介绍了基于SpringBoot 使用 Flink 收发Kafka消息,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-01-01
  • Java中ReUtil正则表达式工具库的使用

    Java中ReUtil正则表达式工具库的使用

    ReUtil是Hutool库中的正则表达式工具类,提供了多种常用正则表达式操作方法,下面就来介绍一下ReUtil的使用,具有一定的参考价值,感兴趣的可以了解一下
    2025-02-02
  • Java高效映射工具MapStruct的使用示例

    Java高效映射工具MapStruct的使用示例

    MapStruct 是一个 Java 注解处理器,用于在不同 Java Beans 或数据传输对象(DTOs)之间自动生成类型安全的映射代码,这是一个编译时映射框架,意味着它利用注解在编译时生成代码,本文将给大家介绍一下Java注解处理器MapStruct的使用示例,需要的朋友可以参考下
    2023-12-12

最新评论