Concatenating lists in Java

Java Program to Join Two Lists

In this program, you'll learn different techniques to join two lists in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

  • Java List
  • Java ArrayList Class
  • Java ArrayList addAll[]

Example 1: Join Two Lists using addAll[]

import java.util.ArrayList; import java.util.List; public class JoinLists { public static void main[String[] args] { List list1 = new ArrayList[]; list1.add["a"]; List list2 = new ArrayList[]; list2.add["b"]; List joined = new ArrayList[]; joined.addAll[list1]; joined.addAll[list2]; System.out.println["list1: " + list1]; System.out.println["list2: " + list2]; System.out.println["joined: " + joined]; } }

Output

list1: [a] list2: [b] joined: [a, b]

In the above program, we used List's addAll[] method to join lists list1 and list2 to the joined list.

Example 2: Join Two Lists using union[]

import java.util.ArrayList; import java.util.List; import org.apache.commons.collections.ListUtils; public class JoinLists { public static void main[String[] args] { List list1 = new ArrayList[]; list1.add["a"]; List list2 = new ArrayList[]; list2.add["b"]; List joined = ListUtils.union[list1, list2]; System.out.println["list1: " + list1]; System.out.println["list2: " + list2]; System.out.println["joined: " + joined]; } }

The output of this program is the same as Example 1.

In the above program, we used union[] method to join the given lists to joined.

Example 3: Join Two Lists using stream

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 list1 = new ArrayList[]; list1.add["a"]; List list2 = new ArrayList[]; list2.add["b"]; List 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 as Example 1.

In the above program, we used Stream's concat[] method to join two lists converted to streams. Then, we convert them back to List using toList[].

Video liên quan

Chủ Đề