How to read values ​​through a stream

I am trying to take a stream of objects that have a variable vote(from 0 to 100). I am trying to count the cases of each of dozens of places. eg:

23,44,48 returns 0:1,  1:2,  0:3,  2:4,...

What am I doing wrong here?

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

public class NewClass {
        public static void main(String[] args){
            class Temp{
                Long vote=ThreadLocalRandom.current().nextLong(100);
            }

            ArrayList<Temp> t=new ArrayList(); 
            t.add(new Temp());
            t.add(new Temp());
            t.add(new Temp());

            Map<Integer, Long> counters = t.stream()
                                       .collect(Collectors.groupingBy(p -> { 
                    return ((int)p.vote/10);
                }, Collectors.counting()));

            Collection<Long> values = counters.values();
            Integer[] res = values.toArray(new Long[values.size()]);
        }
}
+4
source share
1 answer

There seems to be two errors in your code and one warning for using raw ArrayList.

The first problem on this line is:

return ((int)p.vote/10);

p.votehas a type Long, and you cannot attribute it to a type int. This can be solved with:

p -> p.vote.intValue() / 10

The second problem is that the variable resmust be of type Long[]not Integer[].

Finally, the warning can be erased by changing this:

ArrayList<Temp> t = new ArrayList(); 

:

ArrayList<Temp> t = new ArrayList<>();

Full code:

ArrayList<Temp> t = new ArrayList<>();
t.add(new Temp());
t.add(new Temp());
t.add(new Temp());

Map<Integer, Long> counters = 
               t.stream()
                .collect(Collectors.groupingBy(p -> p.vote.intValue()/10, 
                         Collectors.counting()));

Collection<Long> values = counters.values();
Long[] res = values.toArray(new Long[values.size()]);
+3
source

Source: https://habr.com/ru/post/1694116/


All Articles