假设我有三个列表:
a = {a, b, c, d, e}
b = {A, B, C}
c = {aa, bb, cc, dd}
现在我需要从每个列表中取出 3 个元素并将它们插入到一个新列表中,从列表 a 到 c。所以新的列表应该是:
newlist = {a, b, c, A, B, C, aa, bb, cc, d, e, dd}
我想知道在 Java 中最快的方法是什么?
[更新]
统一数据类型,让需求更清晰。
使用Iterables.concat(Iterable<T> ...)
,它会创建所有可迭代对象的实时视图,并将其串联为一个(如果更改可迭代对象,则串联版本也会更改)。Iterables.unmodifiableIterable(Iterable<T>)
然后用(我之前没有看到只读要求)包装连接的迭代。
来自Iterables.concat( .. )
JavaDocs:
将多个可迭代对象组合成一个可迭代对象。返回的迭代器有一个迭代器,它遍历输入中每个迭代器的元素。输入迭代器只有在必要时才会轮询。当对应的输入迭代器支持时,返回的迭代器的迭代器支持 remove()。
虽然这没有明确说明这是一个实时视图,但最后一句暗示它是(Iterator.remove()
仅当支持迭代器支持该方法时才支持该方法,除非使用实时视图,否则这是不可能的)
示例代码:
final List<Integer> first = Lists.newArrayList(1, 2, 3);
final List<Integer> second = Lists.newArrayList(4, 5, 6);
final List<Integer> third = Lists.newArrayList(7, 8, 9);
final Iterable<Integer> all =
Iterables.unmodifiableIterable(
Iterables.concat(first, second, third));
System.out.println(all);
third.add(9999999);
System.out.println(all);
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 999, 9999]
得到结果后,您可以对单个列表进行排序。
归并排序真的很简单。
/**
* Mergesort algorithm.
* @param a an array of Comparable items.
*/
public static void mergeSort( Comparable [ ] a ) {
Comparable [ ] tmpArray = new Comparable[ a.length ];
mergeSort( a, tmpArray, 0, a.length - 1 );
}
/**
* Internal method that makes recursive calls.
* @param a an array of Comparable items.
* @param tmpArray an array to place the merged result.
* @param left the left-most index of the subarray.
* @param right the right-most index of the subarray.
*/
private static void mergeSort( Comparable [ ] a, Comparable [ ] tmpArray,
int left, int right ) {
if( left < right ) {
int center = ( left + right ) / 2;
mergeSort( a, tmpArray, left, center );
mergeSort( a, tmpArray, center + 1, right );
merge( a, tmpArray, left, center + 1, right );
}
}
/**
* Internal method that merges two sorted halves of a subarray.
* @param a an array of Comparable items.
* @param tmpArray an array to place the merged result.
* @param leftPos the left-most index of the subarray.
* @param rightPos the index of the start of the second half.
* @param rightEnd the right-most index of the subarray.
*/
private static void merge( Comparable [ ] a, Comparable [ ] tmpArray,
int leftPos, int rightPos, int rightEnd ) {
int leftEnd = rightPos - 1;
int tmpPos = leftPos;
int numElements = rightEnd - leftPos + 1;
// Main loop
while( leftPos <= leftEnd && rightPos <= rightEnd )
if( a[ leftPos ].compareTo( a[ rightPos ] ) <= 0 )
tmpArray[ tmpPos++ ] = a[ leftPos++ ];
else
tmpArray[ tmpPos++ ] = a[ rightPos++ ];
while( leftPos <= leftEnd ) // Copy rest of first half
tmpArray[ tmpPos++ ] = a[ leftPos++ ];
while( rightPos <= rightEnd ) // Copy rest of right half
tmpArray[ tmpPos++ ] = a[ rightPos++ ];
// Copy tmpArray back
for( int i = 0; i < numElements; i++, rightEnd-- )
a[ rightEnd ] = tmpArray[ rightEnd ];
}