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

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

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

当前回答

稍微简单:

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

其他回答

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

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

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

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

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

下面是一种使用流和java 8的方法,如果你的列表有不同的类型,你想把它们组合成另一种类型的列表。

public static void main(String[] args) {
    List<String> list2 = new ArrayList<>();
    List<Pair<Integer, String>> list1 = new ArrayList<>();

    list2.add("asd");
    list2.add("asdaf");
    list1.add(new Pair<>(1, "werwe"));
    list1.add(new Pair<>(2, "tyutyu"));

    Stream stream = Stream.concat(list1.stream(), list2.stream());

    List<Pair<Integer, String>> res = (List<Pair<Integer, String>>) stream
            .map(item -> {
                if (item instanceof String) {
                    return new Pair<>(0, item);
                }
                else {
                    return new Pair<>(((Pair<Integer, String>)item).getKey(), ((Pair<Integer, String>)item).getValue());
                }
            })
            .collect(Collectors.toList());
}

我最喜欢的方法是,使用流利的api和番石榴:

List<String> combined = ImmutableList.<String>builder().addAll(list1).addAll(list2).build()

简短一点的是:

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