How to get the N largest numbers in array with Java

1 Answer

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

public class MyClass {
    public static ArrayList<Integer> getNLargest(int[] arr, int N) {
        Integer[] iarray = Arrays.stream( arr ).boxed().toArray( Integer[] :: new);
        
        Arrays.sort(iarray, Collections.reverseOrder());
        
        ArrayList<Integer> list = new ArrayList<>(N);
 
        for (int i = 0; i < N; i++)
            list.add(iarray[i]);
     
        return list;
    }

    public static void main(String[] args)
    {
        int[] arr = { 50, 99, 20, 100, 76, 33, 87, 40, 80, 85 };
        int N = 4;
          
        System.out.print(getNLargest(arr, N));
    }
}



 
/*
run:
 
[100, 99, 87, 85]
 
*/

 



answered May 14, 2022 by avibootz
...