Saturday, April 27, 2024
HomeJavaJava program to get SubList from ArrayList - Instance

Java program to get SubList from ArrayList – Instance


Disclosure: This text could include affiliate hyperlinks. While you buy, we could earn a fee.

Generally we want subList from ArrayList in Java. For instance, we’ve got an ArrayList of 10 objects and we solely want 5 objects or we want an object from index 2 to six, these are referred to as subList in Java. Java assortment API supplies a technique to get SubList from ArrayList. On this Java tutorial, we are going to see an instance of getting SubList from ArrayList in Java. On this program, we’ve got an ArrayList which comprises 4 String objects. Later we name ArrayList.subList() technique to get a part of that Listing.

SubList Instance Java

Java SubList Example from ArrayListRight here is full code instance of getting SubList in Java

Java Program to get the a part of a Listing

import java.util.ArrayList;
import java.util.Listing;

/**
 * Java program to get SubList or a spread of checklist from Array Listing in Java
 *
 */

public class GetSubListExample {

       public static void principal(String[] args) {
          ArrayList<String> arrayList = new ArrayList<String>();
         
            //Add components to Arraylist
            arrayList.add(“Java”);
            arrayList.add(“C++”);
            arrayList.add(“PHP”);
            arrayList.add(“Scala”);
                     
            /*
               subList Technique returns sublist from checklist with beginning index to finish index-1
            */

         
            Listing<String> lst = arrayList.subList(1,3);
             
            //show components of sub checklist.
            System.out.println(“Sub checklist comprises : “);
            for(int i=0; i< lst.measurement() ; i++)
              System.out.println(lst.get(i));
           
           
            //take away one aspect from sub checklist
            Object obj = lst.take away(0);
            System.out.println(obj + ” is faraway from sub checklist”);
         
            //print authentic ArrayList
            System.out.println(“After eradicating “ + obj + ” from sub checklist, authentic ArrayList comprises : “);
            for(int i=0; i< arrayList.measurement() ; i++)
              System.out.println(arrayList.get(i));
         
          }

    }

Output:

Sub checklist comprises :

C++

PHP

C++ is faraway from sub checklist

After eradicating C++ from sub checklist, authentic ArrayList comprises :

Java

PHP

Scala

Listing of Java homework train program from java67 weblog

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments