与lambda的计数器在地图java8上

Rob*_*iaz 5 java lambda hashmap java-8 java-stream

我想转换这个:

Map<String,Long> parties = new HashMap<>();
parties.add("a", 1);
...
Long counter = 0l;

for (Long votes : parties.values()){
    counter += votes;
}
Run Code Online (Sandbox Code Playgroud)

对于Java8中的lambda,我尝试使用reduce这样:

parties.entrySet().stream().reduce((stringLongEntry, stringLongEntry2) -> /*Here I Stack*/)
Run Code Online (Sandbox Code Playgroud)

但我不知道如何继续.

PS:我知道我可以做到: parties.values().stream().count();但我想找到另一种方法.

Fed*_*ner 5

如果始终存储1为每个键的值,则总计数将始终与地图的大小匹配.你可以简单地使用它parties.size().

如果为每个键存储不同的值,则计算映射中的值有多少是错误的.你应该总结它们:

long total = parties.values().stream().mapToLong(v -> v).sum();
Run Code Online (Sandbox Code Playgroud)


Nik*_*las 4

尝试使用以下表达式:

counter = parties.values().stream().map((votes) -> votes).reduce(counter, (a, i) -> a+i);
Run Code Online (Sandbox Code Playgroud)

此外,您的代码中几乎没有错误:

  • 使用Map<String,Long> parties = new HashMap<>();是正确的方法,但你的方法没有错误。
  • HashMap没有.add(..)方法,但是.put(..)方法:

    parties.put("a",1L);
    
    Run Code Online (Sandbox Code Playgroud)
  • 由于您的值是Long,因此您必须使用1Lor1l而不是整个1来指定Long值。

  • 我更喜欢写“L”而不是“l”,因为最后一个看起来像“1” (3认同)