stream对多个字段分组_java8 stream如何实现 分组后 多列求和?

本文展示了如何在Java中使用集合框架List和Map,结合Stream API进行数据处理。具体操作包括创建User对象,将它们放入List中,然后通过Stream API将List转换为Map,对User对象的money和pee属性进行聚合操作。
摘要由CSDN通过智能技术生成

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 void setName(String name) {

this.name = name;

}

public String getPass() {

return pass;

}

public void setPass(String pass) {

this.pass = pass;

}

public long getMoney() {

return money;

}

public void setMoney(long money) {

this.money = money;

}

public long getPee() {

return pee;

}

public void setPee(long pee) {

this.pee = pee;

}

}

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

List l1 = new ArrayList(){{

add(u1);add(u2);add(u3);add(u4);

}};

Map collect = l1.stream().collect(Collectors.toMap(k -> k.getName(),

v -> new long[]{v.money, v.pee}, (x, y) -> {

x[0] = x[0] + y[0];

x[1] = x[1] + y[1];

return x;

}));

这样可以吗?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值