Find Second Largest Number in List Java 8

Find Second Largest Number in List Java 8 | Java 8 has many new features like it supports functional programming, a new Streaming API, and new APIs for date and time manipulation, Lambda expression, default methods, method references stream API, and Date Time API was introduced in the Java 8. The stream is an abstract layer introduced by Java 8. Now by using java streams we will find the second largest number in the list.

Example-1:
List = [ 78, 58, 45, 12, 36, 14 ]
The second-largest number in the given list is: 58

Program To Find Second Largest Number in List Java 8

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

public class Main {
   public static void main(String[] args) {
      List<Integer> list = 
               Arrays.asList(78, 58, 45, 12, 36, 14);
      System.out.println("List: " + list);
      Collections.sort(list);
      System.out.println("List after sorting: " + list);
      int secondLargestNumber = list.get(list.size() - 2);
      System.out.println("Second largest number in List is: " 
                        + secondLargestNumber);
   }
}

Output:-

List: [ 78, 58, 45, 12, 36, 14 ]
List after sorting: [ 12, 14, 36, 45, 58, 78 ]
Second largest number in List is: 58

In the above program, first, we have initialized the list with some values. Then we sorted the list in ascending order using the Collections.sort() method. After sorting we get the second last number from the list using get(list.size() – 2).

Let us see a few more examples to find second largest number in list Java 8

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

public class Main {
   public static int getSecondLargest(Integer[] a) {
      List<Integer> list = Arrays.asList(a);
      Collections.sort(list);
      return list.get(list.size() - 2);
   }

   public static void main(String args[]) {
      Integer list1[] = { 1, 2, 5, 6, 3, 2 };
      Integer list2[] = { 44, 66, 99, 77, 33, 22, 55 };
      System.out.println("Second Largest: " 
                  + getSecondLargest(list1));
      System.out.println("Second Largest: " 
                  + getSecondLargest(list2));
   }
}

Output:-

Second Largest: 5
Second Largest: 77

In the above program, we have created an array and passed it to the getSecondLargest() method. This method converts the array to a list, sorts then into the ascending order, and returns the second last number from the list.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.