Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

How to find the N largest elements in an array with Java

1 Answer

0 votes
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;
 
public class MyClass {
 
    public static void kLargest(int[] arr, int N) {
        List<Integer> integerList = Arrays.stream(arr).boxed().
                                    sorted(Collections.reverseOrder()).
                                    collect(Collectors.toList());
         
        for (int i = 0; i < N; i++) {
            System.out.print(integerList.get(i) + " ");
        }
    }
 
    public static void main(String[] args) {
        int[] arr = new int[]{34, 3, 8, 2, 9, 4, 6, 12, 7};
         
        int N = 3;
         
        kLargest(arr, N);
    }
}
 
 
 
 
/*
run:
 
34 12 9 
 
*/

 

 



answered Jul 23, 2022 by avibootz
edited Mar 17, 2023 by avibootz

Related questions

1 answer 101 views
1 answer 172 views
2 answers 72 views
1 answer 102 views
2 answers 205 views
1 answer 113 views
2 answers 139 views
...