Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to understand the use of collect() on IntStream

Tags:

java

java-8

I was trying following code snippet to understand the collect method on IntStream to understand. I was trying to result Hashmap <string, Integer>.

    IntStream.range(0, 4).collect(
            HashMap::new,
            result, t -> result.put("test", somearray.get(t)),
             result -> result.putall()
            );

But compilation complains, can't find symbol variable result.

As per my understanding I need to pass (t, value) -> ... to accumulatore, but I am not able to understand compilation issue as well the use of combiner (3rd argument).

like image 347
subhash kumar singh Avatar asked Feb 04 '23 11:02

subhash kumar singh


1 Answers

You are missing some brackets there... Besides look at the definitions of IntStream.collect it takes two parameters : ObjIntConsumer and BiConsumer. Both take two arguments as input and return nothing.

int somearray[] = new int[] { 1, 5, 6, 7 };

    HashMap<String, Integer> map = IntStream.range(0, 4).collect(
            HashMap::new,
            (result, t) -> result.put("test" + t, somearray[t]),
            (left, right) -> left.putAll(right));
like image 174
Eugene Avatar answered Feb 07 '23 18:02

Eugene