使用列表流和哈希映射进行改进

huangapple go评论77阅读模式
英文:

Improvement with list stream HashMap

问题

使用列表流(list stream)来改进这个方法有没有办法。

@Override
public HashMap<Long, Long> countSearchBetweenDates(OffsetDateTime startPeriod, OffsetDateTime endPeriod) {
    List<Tuple> results = this.repository.countBetweenDate(startPeriod, endPeriod);
    HashMap<Long, Long> companyCountMap = results.stream()
        .collect(Collectors.toMap(
            t -> t.get(0, Long.class),
            t -> t.get(1, Long.class)
        ));
    return companyCountMap;
}

我尝试过,但是由于 lambda 操作符的原因,我就是无法让它工作。

return results.stream().collect(Collectors.toMap(
    t -> t.get(0, Long.class),
    t -> t.get(1, Long.class)
));

Tuple::get(0, Long.class), Tuple::get(1, Long.class) 被标记为错误,但是 IDE 无法识别出问题出在哪里。

英文:

Is there a way of improving this method using list stream.

@Override
public HashMap&lt;Long, Long&gt; countSearchBetweenDates(OffsetDateTime startPeriod, OffsetDateTime endPeriod) {
    List&lt;Tuple&gt; results = this.repository.countBetweenDate(startPeriod, endPeriod);
    HashMap&lt;Long,Long&gt; companyCountMap = new HashMap&lt;&gt;();
    for(Tuple t : results){
        companyCountMap.put(t.get(0,Long.class), t.get(1, Long.class));
    }
    return companyCountMap;
}

I've tried it but I just can't get it to work because of the lambda operator.

 return results.stream().collect(Collectors.toMap(Tuple::get(0, Long.class), Tuple::get(1, Long.class));

The Tuple::get(0, Long.class), Tuple::get(1, Long.class) gets signaled as an error but IDE can't identify what is it.

答案1

得分: 3

你正在使用的语法不正确,正确的语法应该是:

return results.stream()
        .collect(Collectors.toMap(t -> t.get(0, Long.class), t -> t.get(1, Long.class)));
英文:

The syntax you are using is not correct, the correct one should be :

return results.stream()
        .collect(Collectors.toMap(t -&gt; t.get(0, Long.class), t -&gt; t.get(1, Long.class));

huangapple
  • 本文由 发表于 2020年9月18日 15:00:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63950763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定