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

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

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

当前回答

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

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

其他回答

我可以马上把它缩短一行:

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

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

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

下面是一个使用两行代码的java 8解决方案:

List<Object> newList = new ArrayList<>();
Stream.of(list1, list2).forEach(newList::addAll);

请注意,在以下情况下不应使用此方法

newList的来源是未知的,它可能已经与其他线程共享 修改newList的流是并行流,对newList的访问不是同步的,也不是线程安全的

由于副作用的考虑。

上述两个条件都不适用于上述连接两个列表的情况,因此这是安全的。

基于我对另一个问题的回答。

我们可以用两种方法使用java8连接两个列表。

    List<String> list1 = Arrays.asList("S", "T");
    List<String> list2 = Arrays.asList("U", "V");

1)使用concat:

    List<String> collect2 = Stream.concat(list1.stream(), list2.stream()).collect(toList());
    System.out.println("collect2 = " + collect2); // collect2 = [S, T, U, V]

2)使用flatMap:

    List<String> collect3 = Stream.of(list1, list2).flatMap(Collection::stream).collect(toList());
    System.out.println("collect3 = " + collect3); // collect3 = [S, T, U, V]

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

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兼容的(尽管我还没有测试)。也不建议用于生产代码;-)