How to Get Substring Items Within Arraylist in Java?
Last Updated :
02 Feb, 2024
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
import java.util.ArrayList;
public class GFGSubstringArrayList {
public static void main(String[] args) {
ArrayList<String> mainList = new ArrayList<>();
mainList.add( "Programming" );
mainList.add( "Java" );
mainList.add( "Spring" );
mainList.add( "SpringBoot" );
int startIndex = 3 ;
int endIndex = 5 ;
ArrayList<String> substringList = getSubstrings(mainList, startIndex, endIndex);
System.out.println( "Original ArrayList: " + mainList);
System.out.println( "Substrings ArrayList: " + substringList);
}
private static ArrayList<String> getSubstrings(ArrayList<String> list, int startIndex, int endIndex) {
ArrayList<String> substringList = new ArrayList<>();
for (String str : list) {
if (str.length() >= endIndex) {
substringList.add(str.substring(startIndex, endIndex));
} else {
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.
Share your thoughts in the comments
Please Login to comment...