Tuesday, 15 August 2023

Java program to find the Second largest number in an Array or List

     Given an unsorted array of an integers or a List, to write a Java program to find the second largest number or element from the Array or a List

1) Given input is an array of integers

import java.util.Arrays;

public class SecondLargest {

	public static void main(String[] args) {	
		SecondLargest secondLargest = new SecondLargest();
		int[] array = { 2, 8, 3, 4, 5, 7 };
		System.out.println("Second largest number - " + secondLargest.findSecondLargestNumber(array));
	}

	private int findSecondLargestNumber(int[] array) {
		Arrays.sort(array);
		return array[array.length - 2];
	}

}

Output :- Second largest number - 7


2) Given input is a list

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SecondLargest {

	public static void main(String[] args) {

		SecondLargest secondLargest = new SecondLargest();
		List<Integer> list = Arrays.asList(new Integer[] { 2, 8, 3, 4, 5, 7 });
		System.out.println("Second largest number - " 
					+ secondLargest.findSecondLargestNumber(list));
	}

	private int findSecondLargestNumber(List<Integer> listOfIntegers) {
		Collections.sort(listOfIntegers);
		return listOfIntegers.get(listOfIntegers.size() - 2);
	}

}

Output:- Second largest number - 7

3) Given input as a List, find second largest number using Stream(Java8)

import java.util.Arrays;
import java.util.List;

public class SecondLargest {

	public static void main(String[] args) {

		SecondLargest secondLargest = new SecondLargest();
		List<Integer> list = Arrays.asList(new Integer[] { 2, 8, 3, 4, 5, 7 });
		System.out.println("Second largest number - " 
					+ secondLargest.findSecondLargestNumber(list));
	}

	private int findSecondLargestNumber(List<Integer> listOfIntegers) {
		return listOfIntegers.stream().sorted()
				.skip(listOfIntegers.size() - 2)
				.findFirst()
				.get();
	}

}

Output:- Second largest number - 7.


Thank you for visiting the blog.

Related page:-

No comments:

Post a Comment