我试图在一个范围内计数值,我正在接近,但我不知道如何输出0。
input: 12,34
output:
0 (no values from 0-9)
1 (12 is between 10-19)
0
1 (34 between 30-39)
... (my values are guaranteed to be between 0-100)到目前为止我的代码是:
package javaapplication2;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
public class JavaApplication2 {
public static void main(String[] args){
//generating sample data------------------------------
class Temp{
Long vote=ThreadLocalRandom.current().nextLong(100);
public long getVote(){
System.out.println(vote);
return vote;
}
}
ArrayList<Temp> t = new ArrayList<>();
t.add(new Temp());
t.add(new Temp());
t.add(new Temp());
//end generating data------------------------------------
Map<Integer, Long> counters = t.stream()
.collect(Collectors.groupingBy(p -> ((int)p.getVote())/10,
Collectors.counting()));
Collection<Long> values = counters.values();
Long[] res = values.toArray(new Long[values.size()]);
for(Long l:res)
System.out.println(l.toString());
}
}发布于 2018-02-26 04:14:32
要使结果包含0,可以将范围从0到10的流映射到实际结果:
Map<Integer, Long> map = t.stream()
.collect(Collectors.groupingBy(p -> ((int) p.getVote())/10,
Collectors.counting()));
Map<Integer, Long> result = IntStream.range(0, 10).boxed()
.collect(Collectors.toMap(Function.identity(), i -> map.getOrDefault(i, 0L)));https://stackoverflow.com/questions/48980920
复制相似问题