Listlist = new ArrayList<>(); list.add("dogs"); list.add("cats"); list.add("fish"); list.add("birds"); List subList = list.subList(1, 3); System.out.println(subList); // Output: [cats, fish]
ListIn this example, we create a List of Integer and retrieve a section of the List containing only 10, 1 and 9. We then sort the subList in ascending order and print the subList and the original List. As we can see, only the subList is sorted. The subList() method is useful when we want to perform operations on a section of a List without modifying the original List. It is also a useful method to use when we want to retrieve only a portion of a List.list = new ArrayList<>(); list.add(5); list.add(10); list.add(1); list.add(9); list.add(4); List subList = list.subList(1, 4); Collections.sort(subList); System.out.println(subList); // Output: [1, 9, 10] System.out.println(list); //Output: [5, 1, 9, 4, 10]