java 多重属性,Java 8添加了对象列表的多个属性的值

Lets say I have a class below with getters and setters but with only default constructor.

Note: I'm not allowed to change the structure of this class.

class Target {

private String year;

private String month;

private String name;

private double target;

private double achieved;

public String getYear() {

return year;

}

public void setYear(String year) {

this.year = year;

}

public String getMonth() {

return month;

}

public void setMonth(String month) {

this.month = month;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public double getTarget() {

return target;

}

public void setTarget(double target) {

this.target = target;

}

public double getAchieved() {

return achieved;

}

public void setAchieved(double achieved) {

this.achieved = achieved;

}

}

I have to add the Target and Achieved columns values based on year and Name.

Year Month Name Target Achieved

2018 8 Joey 50.00 10.00

2018 9 Joey 200.00 100.00

2018 9 Fred 200.00 150.00

2018 9 Fred 20.00 50.00

So the output would be:

Year Month Name Target Achieved

2018 8 Joey 50.00 10.00

2018 9 Joey 200.00 100.00

2018 9 Fred 220.00 200.00

I've seen an example on how I could achieve something like this if I had a constructor that accepts parameters but I'm not so clear on the concept Group by and sum objects like in SQL with Java lambdas?:

How do I achieve this with just the default constructor to get same type List but with calculated values of multiple columns?

解决方案

It seems that you need to group based on three things: Year, Month and Name, so this could look like this:

Collection merged = yourListOfTargets

.stream()

.collect(Collectors.toMap(

t -> List.of(t.getYear(), t.getMonth(), t.getName()),

Function.identity(),

(left, right) -> {

left.setTarget(left.getTarget() + right.getTarget());

left.setAchieved(left.getAchieved() + right.getAchieved());

return left;

}))

.values();

As Federico mentions in comments, this will alter your elements in the initial List. You might be OK with it, but if you are not, you need to replace Function.identity() with a copying Function that would create a new Target from an existing one.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值