Java Program to Access the Part of List as List
A List is an ordered sequence of elements stored together to form a collection. A list can contain duplicate as well as null entries. A list allows us to perform index-based operations, that is additions, deletions, manipulations, and positional access. Java provides an in-built interface <<java.util>> to perform list as well as other class-based functions.
- The naive approach by maintaining the start and end index.
- Using subList() method.
- Elements are accessed at the required indexes of the list.
- Add them to a new empty list created.
- The start and end index values are used to access the part of the list required. By default, the indexes are assumed to start at 0.
This approach requires an additional space of maintaining a new list to store the sublist desired.
The original list contents : 1 7 8 2 11 3 66 30 The sublist contents : 8 2 11 3
Time Complexity: O(n)
Space Complexity: O(n) where n is the size of the list.
Method 2: Java provides us with an in-built method sublist() to access the elements belonging to the specified range of index values. The method is provided by the ArrayList package.
public List subList(int fromIndex, int toIndex)
- fromIndex = start index
- toIndex = endIndex
Return Type: A list of the required elements. The method access all the elements in the range fromIndex to toIndex-1. If fromIndex is equal to toIndex, an empty list is returned.
The original list contents : Are you working! hard Geeeks? The sublist contents : Are you working!
Time Complexity: O(n) when n is no of elements in the list
Auxiliary Space: O(n)