如何使用流

时间:2018-02-26 03:13:36

标签: java collections

我正在尝试计算范围内的值,我越来越接近,但我无法弄清楚如何输出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());
    }
}

0 个答案:

没有答案