我对java真的很陌生,而且正在慢慢学习,所以不确定是否有明显的方法可以做到这一点,但我基本上有两个列表,我想将它们合并在一起形成一个列表。
为此,Python 代码使用了一个名为 zip 的函数。假设我有 list1 = 1,2,3,4,5
和 list2= 6,7,8,9,10
..然后我想创建一个新列表类似于 new_list = (1,6), (2,7), (3,8), (4,9), (5,10)
。
我找到了question有类似的问题,但我不想使用外部库,而是想学习如何自己创建这个函数。
最佳答案
通用算法看起来像这样(假设您想要获取 N 个输入列表):
public <T> List<List<T>> zip(List<T> ... lists) {
if(lists.isEmpty()) {
return Collections.<List<T>>emptyList();
}
// validate that the input lists are all the same size.
int numItems = lists[0].size();
for(int i = 1; i < lists.length; i++) {
if(lists[i].size() != numItems) {
throw new IllegalArgumentException("non-uniform-length list at index " + i);
}
}
List<List<T>> result = new ArrayList<List<T>>();
for(int i = 0; i < numItems; i++) {
// create a tuple of the i-th entries of each list
List<T> tuple = new ArrayList<T>(lists.length);
for(List<T> list : lists) {
tuple.add(list.get(i));
}
// add the tuple to the result
result.add(tuple);
}
return result;
}
关于java - 如何创建一个合并其他两个列表的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9519160/