Java - Stream - Collect every N elements

后端 未结 6 1307
忘掉有多难
忘掉有多难 2020-12-30 02:38

I am trying to learn java - stream. I am able to do simple iteration / filter / map / collection etc.

When I was kind of trying to collect every 3 elements and print

6条回答
  •  不知归路
    2020-12-30 03:42

    I solved it like this:

        List list = Arrays.asList("a","b","c","d","e","f","g","h","i","j");
        int groupBy = 3;
    
        AtomicInteger index = new AtomicInteger(0);         
        Map> groups = list.stream()
            .collect(Collectors.groupingBy(cdm -> index.getAndIncrement()/groupBy));
    
        System.out.println(groups);
    

    It prepares a map where the line number is the key and the strings on the line are in the key.

提交回复
热议问题