Java - Stream - Collect every N elements

KitKarson :

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 as shown here in this example, [collect every 3 elements and print and so on...]

    List<String> list = Arrays.asList("a","b","c","d","e","f","g","h","i","j");

    int count=0;
    String append="";
    for(String l: list){
        if(count>2){
            System.out.println(append);
            System.out.println("-------------------");
            append="";
            count=0;
        }
        append = append + l;
        count++;
    }
    System.out.println(append);

output:

abc
-------------------
def
-------------------
ghi
-------------------
j

I am not getting any clue how to do this using stream. Should i implement my own collector to achieve this?

Alexis C. :

You can actually use an IntStream to simulate your list's pagination.

List<String> list = Arrays.asList("a","b","c","d","e","f","g","h","i","j");

int pageSize = 3;

IntStream.range(0, (list.size() + pageSize - 1) / pageSize)
        .mapToObj(i -> list.subList(i * pageSize, Math.min(pageSize * (i + 1), list.size())))
        .forEach(System.out::println);

which outputs:

[a, b, c]
[d, e, f]
[g, h, i]
[j]

If you want to generate Strings, you can use String.join since you are dealing with a List<String> directly:

.mapToObj(i -> String.join("", list.subList(i * pageSize, Math.min(pageSize * (i + 1), list.size()))))

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=449050&siteId=1