条件:不修改原有列表;只使用JDK,没有外部库。单行程序或JDK 1.3版本的加分项。
有没有比这更简单的方法:
List<String> newList = new ArrayList<String>();
newList.addAll(listOne);
newList.addAll(listTwo);
条件:不修改原有列表;只使用JDK,没有外部库。单行程序或JDK 1.3版本的加分项。
有没有比这更简单的方法:
List<String> newList = new ArrayList<String>();
newList.addAll(listOne);
newList.addAll(listTwo);
当前回答
这很简单,只有一行,但是会将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(),
...
}))
不是更简单,但没有调整开销:
List<String> newList = new ArrayList<>(listOne.size() + listTwo.size());
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());
下面是一种使用流和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());
}