鉴于:
List<Integer> a = Arrays.asList(1,2,3);
List<Integer> b = Arrays.asList(1,2,3);
List<Integer> c = Arrays.asList(1,2,3);
List<Integer> d = Arrays.asList(1,2,3);
List<List<Integer>> sample = Arrays.asList(a,b,c,d);
Run Code Online (Sandbox Code Playgroud)
我怎样才能用 java 8 得到这个结果?
[(1,1,1,1),(2,2,2,2),(3,3,3,3)]
Run Code Online (Sandbox Code Playgroud)
/**
* Zips lists. E.g. given [[1,2,3],[4,5,6]], returns [[1,4],[2,5],[3,6]].
* @param listOfLists an N x M list
* @returns an M x N list
*/
static <T> List<List<T>> zip(List<List<T>> listOfLists) {
int size = listOfLists.get(0).size();
List<List<T>> result = new ArrayList<>(size);
for (int i = 0; i < size; ++i)
result.add(
listOfLists.stream()
.map(list -> list.get(i))
.collect(toList()));
return result;
}
Run Code Online (Sandbox Code Playgroud)
如果我们考虑到所有列表都具有相同的大小,那为什么是 Java 8呢?你可以使用一个简单的循环,如下所示:
List<List<Integer>> list = new ArrayList<>();
for(int i = 0; i<a.size(); i++){
list.add(Arrays.asList(a.get(i), b.get(i), c.get(i), d.get(i)));
}
Run Code Online (Sandbox Code Playgroud)
输出
[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
Run Code Online (Sandbox Code Playgroud)
我真的坚持在这里阅读这篇文章Is using Lambda statements 只要有可能在java中是好的实践吗?