Advertisement
jasonpogi1669

Sort First K elements of Collection in Java

Aug 7th, 2022
637
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.51 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class Test {
  5.     public static void main(String[] args) {
  6.         ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(9, 1, 7, 0, 1, 5, 4, 6));
  7.        
  8.         Scanner sc = new Scanner(System.in);
  9.         int k = sc.nextInt();
  10.         sc.close();
  11.        
  12.         if (k > arr.size()) {
  13.             System.out.println("Invalid");
  14.             return;
  15.         }
  16.        
  17.         //sort first k elements
  18.         Collections.sort(arr.subList(0, k));
  19.        
  20.         for (Integer x : arr) {
  21.             System.out.print(x + " ");
  22.         }
  23.         System.out.println();
  24.     }
  25. }
  26.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement