To create a sublist in Java, you can use the subList method of the List interface.
Here is an example of how you can create a sublist of a List in Java:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Create a sublist of the first five elements of the list List<Integer> sublist = numbers.subList(0, 5); System.out.println(sublist); // Outputs [1, 2, 3, 4, 5]
This code creates a List called numbers with the elements 1 through 10, and then creates a sublist of the first five elements using the subList method. The subList method takes two arguments: the start index (inclusive) and the end index (exclusive) of the sublist.
The subList method returns a view of the original List, so any changes made to the sublist will be reflected in the original list. If you want to create a new list that is a copy of the sublist, you can use the List constructor:
List<Integer> sublist = new ArrayList<>(numbers.subList(0, 5));
This code creates a new ArrayList called sublist that is a copy of the sublist of the numbers list.
You can also use the List constructor to create a sublist from an array:
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
List<Integer> numbers = Arrays.asList(array);
List<Integer> sublist = new ArrayList<>(numbers.subList(0, 5));
System.out.println(sublist); // Outputs [1, 2, 3, 4, 5]
This code creates a List called numbers from the array using the asList method of the Arrays class, and then creates a sublist of the first five elements using the subList method and the List constructor.