爲了使用併發計算,有時候須要對list作拆分。而java中默認的subList方法知足不了這種需求,那就本身動手寫一個吧。java
package demo18; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.python.google.common.collect.Lists; /** * 對List進行拆分,用於分佈式計算 * * @author mengfeiyang * */ public class ListSplit<T> { public List<List<T>> split(List<T> sList, int num) { List<List<T>> eList = new ArrayList<List<T>>(); List<T> gList; int size = (sList.size()) / num; int size2 = (sList.size()) % num; int j = 0; int xx = 0; for (int i = 0; i < num; i++) { gList = new ArrayList<T>(); for (j = xx; j < (size + xx); j++) { gList.add(sList.get(j)); } xx = j; eList.add(gList); } if (size2 != 0) { gList = new ArrayList<T>(); for (int y = 1; y < size2 + 1; y++) { gList.add(sList.get(sList.size() - y)); } eList.add(gList); } return eList; } public static void main(String[] args) { //構造一個待拆分的list List<String> ll = Lists.newArrayList("a","b","c","d","e"); ListSplit<String> ls = new ListSplit<String>(); //把list平均拆分紅2個,若不能平均拆分,多出的一個會單獨保存到一個list中。 List<List<String>> li = ls.SplitList(ll, 2); for(List<String> l : li){ System.out.println(Arrays.toString(l.toArray()));//打印出被拆分後的每一個list中的值 } } }
輸出:python