根据一个字段,对多个字段进行求和
直接代码,可运行
public class MultiFieldSum {
public static void main(String[] args) {
User u1 = new User("lrj", "11", 10, 4);
User u2 = new User("ldh", "12", 20, 5);
User u3 = new User("lrj", "13", 30, 6);
User u4 = new User("ldh", "14", 40, 7);
User u5 = new User("ldh", "10", 10, 2);
List<User> l1 = new ArrayList<User>() {{
add(u1);
add(u2);
add(u3);
add(u4);
add(u5);
}};
Map<String, long[]> collect = l1.stream().collect(Collectors.toMap(k -> k.getName(), v -> new long[]{v.getMoney(), v.getPee()}, (x, y) -> {
x[0] = x[0] + y[0];
x[1] = x[1] + y[1];
return x;
}));
for (String key : collect.keySet()) {
System.out.println(key);
}
System.out.println("===========");
System.out.println(collect.get("ldh")[0]);
System.out.println(collect.get("ldh")[1]);
}
}
class User {
private String name;
private String pass;
private long money;
private long pee;
public User(String name, String pass, long money, long pee) {
this.name = name;
this.pass = pass;
this.money = money;
this.pee = pee;
}
public String getName() {
return name;
}
public long getMoney() {
return money;
}
public long getPee() {
return pee;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", pass='" + pass + '\'' +
", money=" + money +
", pee=" + pee +
'}';
}
}