一 需求
以 name phone address 三个字段为关键字,分组计算 scope 的和。
name |
phone |
address |
scope |
tom |
15687675434 |
北京 |
100 |
tom |
15687675434 |
北京 |
50 |
tom |
13654345654 |
上海 |
77 |
jerry |
15976543454 |
苏州 |
30 |
erry |
15976543454 |
苏州 |
40 |
二 代码
package com.cakin.javademo;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* @ClassName: GroupSum
* @Description: 多字段分组,单字段求和 https://blog.csdn.net/xp_lx1/article/details/109624697
* @Date: 2021/3/13
* @Author: cakin
*/
public class GroupSum {
/**
* 功能描述:多字段分组,单字段求和 测试
*
* @author cakin
* @date 2021/3/14
* @param args 命令行
*/
public static void main(String[] args) {
List<User> users = new ArrayList<>();
users.add(new User("tom", "15687675434", "北京", 100l));
users.add(new User("tom", "15687675434", "北京", 50l));
users.add(new User("tom", "13654345654", "上海", 77l));
users.add(new User("jerry", "15976543454", "苏州", 30l));
users.add(new User("jerry", "15976543454", "苏州", 40l));
List<User> userList = new ArrayList<>();
// 以 name phone address 三个字段为关键字,分组计算 scope 的和。
users.stream().collect(Collectors
.groupingBy(user -> new User(user.getName(), user.getPhone(), user.getAddress()), Collectors.summarizingLong(user -> user.getScope())))
.forEach((k, v) -> {
k.setScope(v.getSum());
userList.add(k);
});
for (User user : userList) {
System.out.println(user);
}
}
}
/**
* @ClassName: User
* @Description: 用户类
* @Date: 2021/3/13
* @Author: cakin
*/
class User {
public String name;
public String phone;
public String address;
public 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;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Long getScope() {
return scope;
}
public void setScope(Long scope) {
this.scope = scope;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", phone='" + phone + '\'' +
", address='" + address + '\'' +
", scope=" + scope +
'}';
}
@Override
public int hashCode() {
return Objects.hash(name, phone, address);
}
@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);
}
}
三 测试
User{name='tom', phone='15687675434', address='北京', scope=150}
User{name='jerry', phone='15976543454', address='苏州', scope=70}
User{name='tom', phone='13654345654', address='上海', scope=77}