How to Get Substring Items Within Arraylist in Java?
In Java, ArrayList is the pre-defined class of the Java collection framework, and it is part of java.util package. ArrayList can be used to add or remove an element dynamically in a Java program. It can be dynamically based on the elements added or removed from the ArrayList.
In this article, we will be discussing how to get substring items within ArrayList in Java.
Methods to get the substrings items within ArrayList
Two methods are mostly used to implement to get the substrings items within ArrayList in the Java program.
- add(): It is a pre-defined method of the ArrayList that can be used to add the elements to the ArrayList.
- substring(startIndex, endIndex): It is also an in-built method, and it can be used to generate the substring with the specified starting index and ending index parameter of the method.
Java Program to Get the Substrings Items within ArrayList
Java
// Java Program to Get Substrings from an ArrayList of Strings import java.util.ArrayList; public class GFGSubstringArrayList { // Main method public static void main(String[] args) { // Create the ArrayList of Strings named as mainList ArrayList<String> mainList = new ArrayList<>(); // Adding values to mainList mainList.add( "Programming" ); mainList.add( "Java" ); mainList.add( "Spring" ); mainList.add( "SpringBoot" ); // Define the startIndex and endIndex of the substring int startIndex = 3 ; int endIndex = 5 ; // Get substrings from the ArrayList ArrayList<String> substringList = getSubstrings(mainList, startIndex, endIndex); // Print the result System.out.println( "Original ArrayList: " + mainList); System.out.println( "Substrings ArrayList: " + substringList); } // Method to get substrings from an ArrayList of Strings private static ArrayList<String> getSubstrings(ArrayList<String> list, int startIndex, int endIndex) { ArrayList<String> substringList = new ArrayList<>(); for (String str : list) { // Check if the string is long enough for the specified indices if (str.length() >= endIndex) { substringList.add(str.substring(startIndex, endIndex)); } else { // Handle the case where the string is shorter than the specified indices substringList.add( "No SubString" ); } } return substringList; } } |
Output
Original ArrayList: [Programming, Java, Spring, SpringBoot] Substrings ArrayList: [gr, No SubString, in, in]
Explanation:
- In the above program, we are getting the substring item within the ArrayList.
- We have created the ArrayList and added the elements into the ArrayList.
- After that defined one more method to convert the substrings with the specified starting index and ending of the parameters of the substring in the program.