Java 8添加对象列表的多个属性的值

时间:2018-09-23 10:03:35

标签: java lambda java-8 java-stream

让我们说我下面有一个带有getter和setter的类,但是只有默认的构造函数。

注意:我不允许更改此类的结构。

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

我必须根据年份和名称添加“目标”和“实现”列的值。

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

所以输出将是:

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

我已经看到了一个示例,该示例说明了如果我有一个接受参数的构造函数,但我对Group by and sum objects like in SQL with Java lambdas?的概念不太清楚:

如何仅使用默认构造函数来获取相同类型List<Target>但使用多个列的计算值来实现此目标?

2 个答案:

答案 0 :(得分:8)

似乎您需要基于以下三个方面进行分组:router.route ('/friends/:id').get((req,res) => { Friend.findById(req.params.id, (err,friend) => { if (err) console.log(err); else res.json(friend); }); }); router.route ('/friends/:UserMain').get((req,res) => { Friend.find({UserMain: req.params.UserMain}, function (err, friends) { if(err) { console.log(err) } else { res.json(friends) } }) }); Year,因此看起来像这样:

Month

正如Federico在评论中提到的那样,这将改变您在初始Name中的元素。您可能对此表示满意,但如果不满意,则需要用一个复制函数替换Collection<Target> 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(); ,该函数将从现有的复制函数中创建一个新的List

答案 1 :(得分:0)

Traceback (most recent call last):
  File "mtrand.pyx", line 1115, in mtrand.RandomState.choice
TypeError: 'dict_keys' object cannot be interpreted as an integer

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    loot = container().open()
  File "test.py", line 8, in __init__
    self.item = choice(self.inv(choice(self.probabilities.keys(), p=self.probabilities.values())))
  File "mtrand.pyx", line 1117, in mtrand.RandomState.choice
ValueError: 'a' must be 1-dimensional or an integer