Computer >> Computer tutorials >  >> Programming >> Java

Java Program to Join Two Lists

In this article, we will understand how to join two lists. The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.

Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.

Below is a demonstration of the same −

Suppose our input is

First list is defined as: [Java, Python]
Second list: [Mysql, Redshift]

The desired output would be

The list after joining two strings: [Java, Python, Mysql, Redshift]


Step 1 - START
Step 2 - Declare two lists namely input_list_1 and input_list_2
Step 3 - Define the values.
Step 4 - Using the function join_lists() and passing both thelists as parametes, we join the two lists.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

import java.util.LinkedList;
public class Demo {
   static void get_element(LinkedList<String> input_list, int index){
      String result_string = input_list.get(index);
      System.out.print("The element at index 3 is: " + result_string);
   public static void main(String[] args) {
      LinkedList<String> input_list = new LinkedList<>();
      System.out.println("The list is defined as: " + input_list);
      int index = 3;
      get_element(input_list, index);


The list is defined as: [Python, Java, Scala, Java, JavaScript]
The element at index 3 is: Java

Example 2

Here, we encapsulate the operations into functions exhibiting object oriented programming.

import java.util.ArrayList;
import java.util.List;
public class Demo {
   static void join_lists(List<String> input_list_1, List<String> input_list_2){
      List<String> result_list = new ArrayList<String>();
      System.out.println("\nThe list after joining two strings: " + result_list);
   public static void main(String[] args) {
      List<String> input_list_1 = new ArrayList<String>();
      System.out.println("The first list is defined as: " + input_list_1);
      List<String> input_list_2 = new ArrayList<String>();
      System.out.println("The second list is defined as: " + input_list_2);
      join_lists(input_list_1, input_list_2);


The first list is defined as: [Java, Python]
The second list is defined as: [Mysql, Redshift]

The list after joining two strings: [Java, Python, Mysql, Redshift]