条件:不修改原有列表;只使用JDK,没有外部库。单行程序或JDK 1.3版本的加分项。

有没有比这更简单的方法:

List<String> newList = new ArrayList<String>();
newList.addAll(listOne);
newList.addAll(listTwo);

当前回答

在Java 8中(另一种方式):

List<?> newList = 
Stream.of(list1, list2).flatMap(List::stream).collect(Collectors.toList());

其他回答

这很简单,只有一行,但是会将listTwo的内容添加到listOne。你真的需要把内容放到第三个列表里吗?

Collections.addAll(listOne, listTwo.toArray());

我不是说这很简单,但你提到了一句话的奖励;-)

Collection mergedList = Collections.list(new sun.misc.CompoundEnumeration(new Enumeration[] {
    new Vector(list1).elements(),
    new Vector(list2).elements(),
    ...
}))

发现这个问题寻找连接任意数量的列表,不介意外部库。所以,也许它会帮助其他人:

com.google.common.collect.Iterables#concat()

如果您想将相同的逻辑应用于一个for()中的多个不同的集合,则此方法非常有用。

在一般情况下,如果不介绍您自己的实用程序方法,我无法改进双行程序,但如果您确实有字符串列表,并且您愿意假设这些字符串不包含逗号,您可以使用这个长一行程序:

List<String> newList = new ArrayList<String>(Arrays.asList((listOne.toString().subString(1, listOne.length() - 1) + ", " + listTwo.toString().subString(1, listTwo.length() - 1)).split(", ")));

如果去掉泛型,这应该是JDK 1.4兼容的(尽管我还没有测试)。也不建议用于生产代码;-)

在Java 8中(另一种方式):

List<?> newList = 
Stream.of(list1, list2).flatMap(List::stream).collect(Collectors.toList());