Unable to understand using collect () for IntStream

I tried to execute a piece of code to understand a method collecton IntStreamto understand. I tried to get it Hashmap <string, Integer>.

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

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

According to my understanding, I need to pass (t, value) -> ...in accumulatore, but I can not understand the compilation problem, as well as the use of the combiner (3rd argument).

+4
source share
2 answers

You are missing some brackets there ... Also, look at the definitions IntStream.collect, it takes two parameters: ObjIntConsumerand 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));
+8

: .

, , result collect(?,result,?,?).

# collect

combiner a BiConsumer<R,R>, , - 2 .

, , . - , . @Eugene .

a combiner . , . :

public class StreamCollectingTest {
    @Test
    public void combinerNeverBeCalledInSequentialStream()  {
        List<Integer> somearray = Arrays.asList(2, 4, 6, 8);

        Map<String, Object> map = IntStream.range(0, 4).collect(
            HashMap::new,
            (result, it) -> result.put("test", somearray.get(it)),
            (result1, result2) -> fail("Combiner was called in sequential stream!")
        );

        // maybe your logic is wrong, the size of map is always less than 2.
        assertThat(map.keySet(), hasSize(1));
    }
}
0

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


All Articles