Java以组的数量将字符串分组

package org.jimmy.autosearch2019.test;

import java.util.ArrayList;

public class Test20190327 {

    public static void main(String[] args) {
        ArrayList<String> strList = new ArrayList<String>();
        for(int i = 1; i < 22; i++) {
            strList.add(i + "");
        }
        int group = 2;
        ArrayList<String> groupedStrList = getGroupStrs(strList, group);
        for(int i = 0; i < groupedStrList.size(); i++) {
            System.out.println(groupedStrList.get(i));
        }
    }

    public static ArrayList<String> getGroupStrs(ArrayList<String> strList, int group){
        ArrayList<String> groupedStrList = new ArrayList<String>();
        String strs = "";
        for(int i = 0; i < strList.size(); i++) {
            if(i % group == group - 1) {
                strs += strList.get(i);
                groupedStrList.add(strs);
                strs = "";
            }else {
                strs += strList.get(i) + ",";
            }
            if(i == strList.size() - 1) {
                if(strs.lastIndexOf(",") > 0 && strs.lastIndexOf(",") == strs.length() - 1) {
                    strs = strs.substring(0, strs.length() - 1);
                }
                groupedStrList.add(strs);
            }
        }
        return groupedStrList;
    }
    
}

以上就是代码.

效果图:如下

2015年10月-2016年3月 总计:5个月.
2016年11月-2017年6月 总计:7个月.
2017年7月-2018年4月 总计:9个月.
2018年5月-2018年5月 总计:1个月.
2018年6月-2018年12月 总计:6个月.
2019年1月-2019年12月 总计11个月.
2020年2月-2021年2月 总计13个月.
所有总计:5+7+9+1+6+11+13=52个月(4年4个月).
本人认同二元论.我是理想主义者,现实主义者,乐观主义者,有一定的完美主义倾向.不过,一直都是咸鱼(菜鸟),就算有机会,我也不想咸鱼翻身.(并不矛盾,因为具体情况具体分析)
英语,高等数学,考研,其他知识学习打卡交流QQ群:946556683
原文地址:https://www.cnblogs.com/JimmySeraph/p/10612811.html