Problem Statement: Write a Java program that extracts a sublist from an ArrayList, given a start and end index.
Here’s a Java program that extracts a sublist from an ArrayList
given start and end index.
package com.javacodepoint.collection;
import java.util.ArrayList;
import java.util.List;
public class ExtractSublistDemo {
public static void main(String[] args) {
ArrayList<String> originalList = new ArrayList<>();
originalList.add("Apple");
originalList.add("Banana");
originalList.add("Cherry");
originalList.add("Date");
originalList.add("Fig");
System.out.println("Original List: " + originalList);
int startIndex = 1; // Inclusive
int endIndex = 3; // Exclusive
// Extracting a sublist
List<String> sublist = extractSublist(originalList, startIndex, endIndex);
System.out.println("Sublist from index " + startIndex + " to " + endIndex + ": " + sublist);
}
// Method to extract a sublist from an ArrayList
public static <T> List<T> extractSublist(List<T> list, int startIndex, int endIndex) {
if (startIndex < 0 || endIndex > list.size() || startIndex > endIndex) {
throw new IllegalArgumentException("Invalid start or end index");
}
return list.subList(startIndex, endIndex);
}
}
OUTPUT:
Original List: [Apple, Banana, Cherry, Date, Fig]
Sublist from index 1 to 3: [Banana, Cherry]
Explanation:
- Creating the List: We create an
ArrayList
namedoriginalList
and populate it with some strings. - Printing the Original List: We print the contents of the
originalList
usingSystem.out.println()
. - Defining Start and End Indices: We specify the
startIndex
(inclusive) andendIndex
(Exclusive) to define the range of elements we want to extract from theoriginalList
. - Extracting the Sublist: We call the
extractSublist()
method to extract the sublist from theoriginalList
based on the given start and end indices. extractSublist()
Method: This method takes three parameters: the original list (list
), the start index (startIndex
), and the end index (endIndex
).- Input Validation: Inside the method, we perform some input validation to ensure that the start index is not negative, the end index does not exceed the size of the list, and the start index is less than the end index. If any of these conditions are not met, an
IllegalArgumentException
is thrown. - Sublist Extraction: We use the
subList()
method provided by theList
interface to extract the sublist based on the start and end indices. This method returns a view of the original list, containing the elements from the start index (inclusive) up to, but not including, the end index (exclusive). - Printing the Sublist: Finally, we print the contents of the extracted sublist.
By using the subList()
method, the program effectively extracts a sublist from an ArrayList
based on the specified start and end indices.
See also: Find duplicate elements in an ArrayList.