Write a JAVA Program to get the k largest elements in an user entered array.
![Write a JAVA Program to get thek largest elements in an user entered array.](/v2/_next/image?url=https%3A%2F%2Fcontent.bartleby.com%2Fqna-images%2Fquestion%2Fd464166c-887f-4a4f-9688-e19568c869f1%2Fe3325dcf-942b-4110-870b-bfb52c6d9d51%2Fb8sjfup_processed.jpeg&w=3840&q=75)
![](/static/compass_v2/shared-icons/check-mark.png)
// Java code for k largest elements in an array
import java.util.Arrays;
import java.util.Collections;
import java.util.ArrayList;
class LargestElements {
public static void kLargest(Integer[ ] arr, int k)
{
// Sort the given array arr in reverse order
// This method doesn't work with primitive data
// types. So, instead of int, Integer type
// array will be used
Arrays.sort(arr, Collections.reverseOrder());
// Print the first kth largest elements
for (int i = 0; i < k; i++)
System.out.print(arr[i] + " ");
}
public static ArrayList<Integer> kLargest(int[] arr, int k)
{
//Convert using stream
Integer[ ] obj_array = Arrays.stream( arr ).boxed().toArray( Integer[ ] :: new);
Arrays.sort(obj_array, Collections.reverseOrder());
ArrayList<Integer> list = new ArrayList<>(k);
for (int i = 0; i < k; i++)
list.add(obj_array[i]);
return list;
}
public static void main(String[ ] args)
{
Integer arr[ ] = new Integer[ ] { 1, 23, 12, 9,
30, 2, 50 };
int k = 3;
kLargest(arr, k);
//What if primitive datatype array is passed and wanted to return in ArrayList<Integer>
int[ ] prim_array = { 1, 23, 12, 9, 30, 2, 50 };
System.out.print(kLargest(prim_array, k));
}
}
Step by step
Solved in 2 steps
![Blurred answer](/static/compass_v2/solution-images/blurred-answer.jpg)
![Database System Concepts](https://www.bartleby.com/isbn_cover_images/9780078022159/9780078022159_smallCoverImage.jpg)
![Starting Out with Python (4th Edition)](https://www.bartleby.com/isbn_cover_images/9780134444321/9780134444321_smallCoverImage.gif)
![Digital Fundamentals (11th Edition)](https://www.bartleby.com/isbn_cover_images/9780132737968/9780132737968_smallCoverImage.gif)
![Database System Concepts](https://www.bartleby.com/isbn_cover_images/9780078022159/9780078022159_smallCoverImage.jpg)
![Starting Out with Python (4th Edition)](https://www.bartleby.com/isbn_cover_images/9780134444321/9780134444321_smallCoverImage.gif)
![Digital Fundamentals (11th Edition)](https://www.bartleby.com/isbn_cover_images/9780132737968/9780132737968_smallCoverImage.gif)
![C How to Program (8th Edition)](https://www.bartleby.com/isbn_cover_images/9780133976892/9780133976892_smallCoverImage.gif)
![Database Systems: Design, Implementation, & Manag…](https://www.bartleby.com/isbn_cover_images/9781337627900/9781337627900_smallCoverImage.gif)
![Programmable Logic Controllers](https://www.bartleby.com/isbn_cover_images/9780073373843/9780073373843_smallCoverImage.gif)