list如何拆分呢?

杨幂 Java经验 发布时间:2022-05-24 10:30:25 阅读数:11289 1
下文笔者讲述将一个list集合拆分为多个小集合的方法分享,如下所示
实现思路:
    使用list集合中的subList方法
	即可将集合拆分为多个子集合
例:
package com.java265.other;
import java.util.ArrayList;
import java.util.List;
/*
 * list 拆分的示例分享
 * */
public class Test17 {
	/**
	 * java265.com 示例程序
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {

		List<Integer> list = new ArrayList<>();
		int i = 1;
		// 生成集合
		while (i <= 10) {
			list.add(i);
			i++;
		}


		// 拆分为子集合
		int startIndex = 0;
		int endIndex = list.size();
		int subListLength = 3; // 子集合长度
		while (startIndex < endIndex) {
			if (startIndex + subListLength > endIndex) {
				System.out.println(list.subList(startIndex, endIndex).toString());
			} else {
				System.out.println(list.subList(startIndex, startIndex + subListLength).toString());
			}
			startIndex += subListLength;
		}

	}
}

-----运行以上代码,将输出以下信息------
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10]
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202205/16533595033477.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者