Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

java - Splitting list into 4 even separate lists

Currently I’m making a game. I want to evenly split all the players into 4 teams

teams = (List<List<Player>>)Lists.partition((List)players, Lists.partition((List)players, 4).size());

is what I tried so far (using classes from google guava). But that doesn’t work. What I’m trying to do is something like this:

Initial list:

[“jdjdb”,”jsid”,”hsisi”,”hri”,”idt”]

Output lists:

[[“jdjdb”, “jsid”],[“hsisi”],[“hri”], [“idt”]]

And it just adds the leftovers on to any of the lists.

question from:https://stackoverflow.com/questions/65928759/splitting-list-into-4-even-separate-lists

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can try something as follows:

final int size_split = 4;
List<List<String>> result = new ArrayList<>();
for(int i = 0; i < size_split; i++)
    result.add(new ArrayList<>());

int count = 0;
for(String s : list){
    result.get(count % size_split).add(s);
    count++;
}
System.out.println(result);

First initialize the structure that will hold the four lists:

List<List<String>> result = new ArrayList<>();
for(int i = 0; i < size_split; i++)
    result.add(new ArrayList<>());

Then iterate over the elements of the original list, and add them to the positions 0, then 1, then 2, then 3 (and start over again) of the final list i.e., round-robin fashion:

int count = 0;
for(String s : list){
    result.get(count % size_split).add(s);
    count++;
}

A Running example:

public class Main {
    public static void main(String[] arg) {
        List<String> list = new ArrayList<>();
        list.add("jdjdb");
        list.add("jsid");
        list.add("hsisi");
        list.add("hri");
        list.add("idt");

        final int size_split = 4;
        List<List<String>> result = new ArrayList<>();
        for(int i = 0; i < size_split; i++)
            result.add(new ArrayList<>());

        int count = 0;
        for(String i : list){
            result.get(count % size_split).add(i);
            count++;
        }
        System.out.println(result);
    }
}

Output:

[[jdjdb, idt], [jsid], [hsisi], [hri]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...