Java 8 sum list of objects

How do java8 stream group by multiple fields and sum over a single field

the following types of grouping and summation requirements are common in mysql

select a, b, c, sum(d) from t group by a

by sql standards ,b,c column does not use the aggregate function in oracle the middle one will report an error, while the middle one will report an error mysql a loose group by mode, b,c the values are random, and now i have a set java what should an object do if it wants to do something similar

List users; User u1 = new User("tom", "bb", "cc", 100) User u2 = new User("tom", "bb", "cc", 50) User u3 = new User("jerry", "dd", "ee", 30) User u2 = new User("jerry", "dd", "ee",40)

finally, i want to use the stream stream to achieve the following effect of grouping sum

User("tom", "bb", "cc", 150) User("jerry", "dd", "ee", 70)

how to use stream ### problem description

the background of the problem and the methods i have tried

the relevant code

// paste the code text below ( do not use pictures instead of code )

what results do you expect ? what is the actual error message that you see ?

first time answer, hope can help you

User class :

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); } }

rewrite equals and hashCode it's for grouping.
tostring is rewritten to print User the specific attribute value of

the main body function

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); }); } }

the results

User{name='jerry', phone='dd', address='ee', scope=70} User{name='tom', phone='bb', address='cc', scope=150}