有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将ArrayList拆分为组?

我正在尝试实现此方法:

public ArrayList<ArrayList> groupWords(ArrayList<String> scrambledWords, int groupNumber);

该方法将字符串的ArrayList和表示每个组中的字数的数字作为参数,然后返回由ArrayList组成的ArrayList,该ArrayList根据groupNumber参数包含字数组。例如,有一个由20个字符串组成的ArrayList,我想将该ArrayList分成5个组,因此我调用如下方法:

ArrayList<ArrayList> groupedWords = groupWords(ArrayList, 5);

我非常确定我需要一个for循环,其中嵌套另一个for循环,但我不确定如何实现它

如何实现此方法


共 (3) 个答案

  1. # 1 楼答案

    像这样的方法应该有用:

    ArrayList<ArrayList<String>> grouped = new ArrayList<>();
    for(int i = 0; i < words.size(); i++) {
        int index = i/groupSize;
        if(grouped.size()-1 < index)
            grouped.add(new ArrayList<>());
        grouped.get(index).add(words.get(i));
    }
    

    我还没有测试过这段代码,但基本上我使用的是整数除法总是舍入到下一个最低的整数。 示例:4/5=0.8,四舍五入为0

  2. # 2 楼答案

    public ArrayList<ArrayList> groupWords(ArrayList<String> scrambledWords, int groupNumber){
                int arraySize = scrambledWords.size();
                int count = 0;
                ArrayList<ArrayList> result = new ArrayList<>();
                ArrayList<String> subResult = new ArrayList<>();
                for(int i = 0 ; i < arraySize; i++){
                        if(count == groupNumber){
                                count = 0;
                                result.add(subResult);
                                subResult = new ArrayList<>();
                        }
                        subResult.add(scrambledWords.get(i));
                        count++;
                }
                return result;
    }
    

    这是一个简单的Java集合解决方案

    Suggestion : As a return type you should use ArrayList<ArrayList<String>>, and this should be the type for result also.

  3. # 3 楼答案

    {a1}

    List<List<String>> groupedWords = Lists.partition(words, 5);