How to sort the part of a list in Java

1 Answer

0 votes
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;

public class PartialSort {
    public static void main(String[] args) {
        List<Integer> myList = new ArrayList<>(Arrays.asList(15, 6, 19, 8, 3, 7, 9, 1, 4));

        // Sort elements from index 2 to 6 (inclusive of index 2, exclusive of index 7)
        // Since subList is a view of myList, any changes to subList directly affect myList.
        List<Integer> subList = myList.subList(2, 7);
        Collections.sort(subList);

        // Print the updated list
        System.out.println(myList);
    }
}

 
 
/*
run:
 
[15, 6, 3, 7, 8, 9, 19, 1, 4]
 
*/

 



answered Aug 12, 2025 by avibootz
...