第一次回答,希望能帮到你
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}