Java - Stream - Collect every N elements(Java - Stream - 收集每 N 个元素)
问题描述
我正在尝试学习 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()))))
这篇关于Java - Stream - 收集每 N 个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java - Stream - 收集每 N 个元素


- 未找到/usr/local/lib 中的库 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 获取数字的最后一位 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 转换 ldap 日期 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01