我在这里有一个对象列表:
List<Object> list = new ArrayList<Object>();
for(int x = 0; x < 100; x++) {
list.add(x);
}
Collections.shuffle(list);
除了我希望list
的项目均匀分类的其他列表的列表。
List<List<Object>> evenLists = new ArrayList<List<Object>>();
for(int x = 0; x < 4; x++) {
evenLists.add(new ArrayList<Object>());
}
例如。 evenLists
中的每个列表中有25个,但如果evenLists
中有5个列表,则每个列表中有20个
到目前为止我有这个,但它只适用于2个定义的列表,将它们排序为50/50
List<Object> list1 = new ArrayList<Object>();
List<Object> list2 = new ArrayList<Object>();
double chance = 0.5D;
for(Object obj:list) {
if(list1.size() < (list.size() * chance1)) {
list1.add(obj);
} else if(list2.size() < list.size() * chance2) {
list2.add(obj);
} else {
list1.add(obj);
}
}
有没有人有办法达成这个目标?
答案 0 :(得分:2)
创建这样的方法,然后您可以选择要分区的列表数
public List<List<Object>> partionList( List<Object> yourList, int numPartitions)
{
List<List<Object>> resultList = new ArrayList<List<Object>>();
for(int i = 0; i < numPartitions; i++)
resultList.add(new ArrayList<Object>());
int counter = 0;
for(Object o:yourList)
{
resultList.get(counter % numPartitions).add(o);
counter++;
}
return resultList
}
答案 1 :(得分:1)
答案 2 :(得分:1)
我认为你的意思是这样的:
int i=0;
for (Object obj:list) {
EvenLists.get(i % evenLists.size()).add(obj);
i++;
}