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 second largest number in an array with Java

2 Answers

0 votes
import java.util.TreeSet;

public class Main {
    public static int findSecondLargest(int[] arr) {
        if (arr.length < 2) {
            throw new IllegalArgumentException("Array must contain at least two elements");
        }

        TreeSet<Integer> set = new TreeSet<>();
        for (int num : arr) {
            set.add(num);
        }
        
        set.pollLast(); // Remove the largest element
        
        return set.last(); // The new largest element is the second largest in array
    }

    public static void main(String[] args) {
        int[] arr = {42, 7, 93, 58, 29, 61, 17, 84, 36, 75};
        
        System.out.println("The second largest number is: " + findSecondLargest(arr));
    }
}



/*
run:

The second largest number is: 84

*/

 



answered Jan 19, 2025 by avibootz
0 votes
import java.util.Arrays;
import java.util.Random;

public class Main {
    public static void setRandomNumbersInArray(int[] arr) {
        Random rnd = new Random();
        int size = arr.length;

        for (int i = 0; i < size; i++) {
            arr[i] = rnd.nextInt(99) + 1;
            System.out.print(arr[i] + " ");
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[10];

        setRandomNumbersInArray(arr);

        int secondLargest = Arrays.stream(arr)
                                   .distinct()
                                   .boxed()
                                   .sorted((a, b) -> b - a)
                                   .skip(1)
                                   .findFirst()
                                   .orElseThrow();

        System.out.println("\nThe second largest number is: " + secondLargest);
    }
}



/*
run:

24 31 75 31 98 3 20 48 5 59 
The second largest number is: 75

*/

 



answered Jan 19, 2025 by avibootz

Related questions

2 answers 205 views
1 answer 100 views
2 answers 151 views
1 answer 102 views
1 answer 82 views
1 answer 148 views
...