条件:不修改原有列表;只使用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);
当前回答
在一般情况下,如果不介绍您自己的实用程序方法,我无法改进双行程序,但如果您确实有字符串列表,并且您愿意假设这些字符串不包含逗号,您可以使用这个长一行程序:
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的方法,如果你的列表有不同的类型,你想把它们组合成另一种类型的列表。
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());
}
另一个Java 8一行代码:
List<String> newList = Stream.of(listOne, listTwo)
.flatMap(Collection::stream)
.collect(Collectors.toList());
另外,由于Stream.of()是可变的,您可以连接任意多的列表。
List<String> newList = Stream.of(listOne, listTwo, listThree)
.flatMap(Collection::stream)
.collect(Collectors.toList());
简短一点的是:
List<String> newList = new ArrayList<String>(listOne);
newList.addAll(listTwo);
可能并不简单,但有趣而丑陋:
List<String> newList = new ArrayList<String>() { { addAll(listOne); addAll(listTwo); } };
不要在产品代码中使用它……;)
我们可以用两种方法使用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]