javaarraylistsublist

ArrayList sublist method clarification


This is regarding the usage of subList method in an ArrayList.

Consider I am having an array as below:-

int[] prices = {71,11,65,99,21,82};

I am converting the above array to arrayList as below:-

List<Integer> priceList = Arrays.stream(prices).boxed().collect(Collectors.toList());

Now, I want to retrieve the elements from position 3 till end and I apply the sublist as follows:-

priceList.subList(3, priceList.size());
            
for(Integer price: priceList) {
    System.out.println(price);
}

But I am still getting the entire list as output. I thought the arrays.stream.boxed would have returned an unmodifiable list and I tried to change as

new ArrayList<>(Arrays.stream....)

But still, I am getting the same output.

Could someone please help with this issue?


Solution

  • First thing, the method subList won't modify the reference on which it is invoked. That means when you call priceList.subList(3, priceList.size()) the priceList isn't getting modified instead, the method returns a new List based on the range. Since you didn't assign it to a variable you cannot access it. So, when you invoke subList method you will have two lists one will be the main list (priceList which won't be modified) and a new subList.

    Approach-1

    Assign the sub list to a new variable/reference, that way you can use that list in the later portions of the code

    List<Integer> subList = priceList.subList(3, priceList.size());
            
    for(Integer price : subList) {
        System.out.println(price);
    }
    

    Approach-2

    If you don't want the sublist in the later portions of your code, supply the return of the subList method to the for-each loop.

    for(Integer price : priceList.subList(3, priceList.size())) {
        System.out.println(price);
    }