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 个元素
基础教程推荐
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01