Java Program to Find a Sublist in a List

JavaCampus InterviewServer Side ProgrammingProgramming

In this article, we will understand how to find a sublist in a list. A list is an ordered collection that allows us to store and access elements sequentially. It contains the index-based methods to insert, update, delete and search the elements. It can also have the duplicate elements. A part or a subset of list is called sublist.

Below is a demonstration of the same −

Suppose our input is

Input list: [101, 102, 103, 104, 105, 106, 107, 108, 109]
Start Index: 3
End input: 6

The desired output would be

The Elements from 3 index position to 6 index position are: [104, 105, 106]

Algorithm

Step 1 - START
Step 2 - Declare an integer list namely input_list.
Step 3 - Define the values.
Step 4 - Use the function subList(3,6) to create a sublist between index value 3 and 6.
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;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      int index_start=3;
      int index_end=6;
      List<Integer> input_list= new LinkedList<>();
      for (int i=1; i<=9; i++){
      input_list.add(i + 100);
   }
   System.out.println("The list is defined as: "+input_list);
   input_list.subList(index_start,index_end);
   System.out.println("The Elements from " +index_start + " index position to "+index_end +" index position are: "+input_list.subList(3,6));
   }
}

Output

The list is defined as: [101, 102, 103, 104, 105, 106, 107, 108, 109]
The Elements from 3 index position to 6 index position are: [104, 105, 106]

Example 2

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

import java.util.LinkedList;
import java.util.List;
public class Demo {
   static void sublist(List<Integer> input_list, int index_start, int index_end){
      input_list.subList(index_start,index_end);
      System.out.println("The Elements from " +index_start + " index position to "+index_end +" index position are: "+input_list.subList(3,6));
   }
   public static void main(String[] args) {
      int index_start=3;
      int index_end=6;
      List<Integer> input_list= new LinkedList<>();
      for (int i=1; i<=9; i++){
         input_list.add(i + 100);
      }
      System.out.println("The list is defined as: "+input_list);

      sublist(input_list, index_start, index_end);
   }
}

Output

The list is defined as: [101, 102, 103, 104, 105, 106, 107, 108, 109]
The Elements from 3 index position to 6 index position are: [104, 105, 106]
raja
Updated on 30-Mar-2022 07:28:28

Advertisements