stream对多个字段分组_java8 stream 如何按多字段分组,并对一个字段求和

第一次回答,希望能帮到你

User类:

class User {

String name;

String phone;

String address;

Long scope;

public User(String name, String phone, String address) {

this.name = name;

this.phone = phone;

this.address = address;

}

public User(String name, String phone, String address, Long scope) {

this.name = name;

this.phone = phone;

this.address = address;

this.scope = scope;

}

@Override

public String toString() {

return "User{" +

"name='" + name + '\'' +

", phone='" + phone + '\'' +

", address='" + address + '\'' +

", scope=" + scope +

'}';

}

@Override

public boolean equals(Object o) {

if (this == o) return true;

if (o == null || getClass() != o.getClass()) return false;

User user = (User) o;

return Objects.equals(name, user.name) &&

Objects.equals(phone, user.phone) &&

Objects.equals(address, user.address) &&

Objects.equals(scope, user.scope);

}

@Override

public int hashCode() {

return Objects.hash(name, phone, address);

}

}

重写equals和hashCode是为了分组。

重写toString是为了打印User的具体属性值

主体函数

public class MyTest {

public static void main(String[] args) {

ArrayList users = new ArrayList();

users.add(new User("tom", "bb", "cc", 100l));

users.add(new User("tom", "bb", "cc", 50l));

users.add(new User("jerry", "dd", "ee", 30l));

users.add(new User("jerry", "dd", "ee",40l));

users.stream()

.collect(Collectors

.groupingBy(

user -> new User(user.name, user.phone, user.address),

Collectors.summarizingLong(user -> user.scope)

)

)

.forEach((k,v) -> {

k.scope = v.getSum();

System.out.println(k);

});

}

}

运行结果

User{name='jerry', phone='dd', address='ee', scope=70}

User{name='tom', phone='bb', address='cc', scope=150}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值