原文: https://www.programiz.com/java-programming/examples/join-two-lists
import java.util.ArrayList;
import java.util.List;
public class JoinLists {
public static void main(String[] args) {
List<String> list1 = new ArrayList<String>();
list1.add("a");
List<String> list2 = new ArrayList<String>();
list2.add("b");
List<String> joined = new ArrayList<String>();
joined.addAll(list1);
joined.addAll(list2);
System.out.println("list1: " + list1);
System.out.println("list2: " + list2);
System.out.println("joined: " + joined);
}
}
运行该程序时,输出为:
list1: [a]
list2: [b]
joined: [a, b]
在以上程序中,我们使用List
的addAll()
方法将列表list1
和list2
联接到联接列表。
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.ListUtils;
public class JoinLists {
public static void main(String[] args) {
List<String> list1 = new ArrayList<String>();
list1.add("a");
List<String> list2 = new ArrayList<String>();
list2.add("b");
List<String> joined = ListUtils.union(list1, list2);
System.out.println("list1: " + list1);
System.out.println("list2: " + list2);
System.out.println("joined: " + joined);
}
}
该程序的输出是相同的。
在上面的程序中,我们使用union()
方法将给定列表连接到joined
上。
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class JoinLists {
public static void main(String[] args) {
List<String> list1 = new ArrayList<String>();
list1.add("a");
List<String> list2 = new ArrayList<String>();
list2.add("b");
List<String> joined = Stream.concat(list1.stream(), list2.stream())
.collect(Collectors.toList());
System.out.println("list1: " + list1);
System.out.println("list2: " + list2);
System.out.println("joined: " + joined);
}
}
The output of this program is the same.
在上面的程序中,我们使用Stream
的concat()
方法将转换为流的两个列表连接在一起。 然后,我们使用toList()
将它们转换回List
。