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 237 views
1 answer 120 views
2 answers 167 views
1 answer 119 views
1 answer 181 views
1 answer 204 views
1 answer 118 views
...