Java - Stream - 收集每 N 个元素

2022-01-22 00:00:00 java-8 java java-stream

我正在尝试学习 java - 流.我能够做简单的迭代/过滤/映射/收集等.

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

当我尝试收集每 3 个元素并按此示例中所示打印时,[收集每 3 个元素并打印等等...]

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);

输出:

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?

推荐答案

您实际上可以使用 IntStream 来模拟列表的分页.

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);

哪个输出:

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

如果你想生成字符串,你可以使用 String.join 因为你是直接处理一个 List<String>:

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()))))

相关文章