Rilcon42
Rilcon42

Reputation: 9763

how to count values via stream

I am trying to take in a stream of objects which have a variable vote (0 to 100). I am trying to count the occurrences of each to the tens place. 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()]);
        }
}

Upvotes: 4

Views: 81

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56423

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

The first issue is in this line:

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

p.vote is of type Long and you cannot cast it to a type int. This can be solved with:

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

The second issue is that the res variable should be of type Long[] not Integer[].

Finally, the warning can be erased by changing this:

ArrayList<Temp> t = new ArrayList(); 

to this:

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

Complete 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()]);

Upvotes: 3

Related Questions