在两个方向合并两个列表的有效方法是什么,一个以递增方式合并,另一个以递减方式合并。两个列表的长度不同。
List1 = ["eight", "nine"] // first element "eight" should be the starting point
List2 = ["three", "six", "seven", "eight"] // last element "eight" should be the starting point
所以最后的结果是
c= ["eight", "eight", "nine", "seven", "six", "three"]
这不完全是我的代码,但这只是一个例子。此处所有列表均来自每个列表的first-element
。但是我需要一个来自first-element
到last-element
,而另一个应该是last-element
到first-element
List<String> a = [ "one", "two", "three", "four" ];
List<String> b = [ "fee", "fi" ];
List<String> c = [ "broccoli", "tomato", "potato" ];
List<String> d = [ "purple" ];
Iterator<String> interleaved = Iterators.interleave(
a.iterator(), b.iterator(),
c.iterator(), d.iterator() );
int count = 1;
while ( interleaved.hasNext() ) {
System.out.println( count++ + ": " + interleaved.next() );
}
Output:
1: one
2: fee
3: broccoli
4: purple
5: two
6: fi
7: tomato
8: three
9: potato
10: four
答案 0 :(得分:0)
您可以按如下方式使用Collections
:
String[] a = ...;
String[] b = ...;
ArrayList<String> firstList = new ArrayList<String>();
ArrayList<String> secondList = new ArrayList<String>();
Collections.addAll(firstList, a);
Collections.addAll(secondList, b);
Collections.reverse(secondList);
firstList.addAll(secondList);
答案 1 :(得分:0)
List
有一个listIterator()
方法返回ListIterator
,可以通过调用previous()
向后迭代,因此您可以创建自己的类来实现ListIterator
包装另一个ListIterator
,反转迭代顺序,即next()
调用previous()
,反之亦然。