This is the third solution to find the Nth largest number from an array of given integers or doubles or strings. This program defines one generic functional interface, with multiple Lambda expressions utilizes the same based on the data type. The internal logic utilizes the sort method of the Arrays class.
import java.util.Arrays;
//Define the Generic functional interface with SAM 'NthBig'
interface NthBiggestGenerics<T> {
void NthBig(T[] tmp, int x);
}
public class NthLargestGenerics {
// Define the generic function which accepts any datatype for display
private static <T> void dispArray(T[] tmpArray, String type) {
System.out.println();
System.out.println("The array of " + type + " are");
System.out.print("[");
for (int i = 0; i < tmpArray.length; i++)
System.out.print(tmpArray[i] + " ");
System.out.println("]");
}
public static void main(String[] args) {
// Initialized integers in this Array
Integer[] intArray = { 34, 21, 45, 75, 62, 98, 13, 49 };
// Print the Array of integers to the console
dispArray(intArray, "Integers");
/* Define the Lambda expression for the functional interface 'NthBiggest' for
* Integer data type */
NthBiggestGenerics<Integer> Nb1 = ((numArr, pos) -> {
Arrays.sort(numArr);
System.out.println("The " + pos + "th largest entity in Array is=" + numArr[numArr.length - pos]);
});
Nb1.NthBig(intArray, 4);
// Initialized floats in this Array
Double[] doubleArray = { 34.0, 21.0, 45.0, 75.0, 62.0, 98.0, 13.0, 49.0 };
// Print the Array of doubles to the console
dispArray(doubleArray, "Doubles");
/* Define the Lambda expression for the functional interface 'NthBiggest' for
* Double data type */
NthBiggestGenerics<Double> Nb2 = ((doubleArr, pos) -> {
Arrays.sort(doubleArr);
System.out.println("The " + pos + "th largest entity in Array is=" + doubleArr[doubleArr.length - pos]);
});
Nb2.NthBig(doubleArray, 5);
// Initialized Strings in this Array
String[] strArray = { "MIKE", "DAVE", "JOHN", "RAMAA", "SANJAY", "RUSS", "NAGENDRA" };
// Print the Array of strings to the console
dispArray(strArray, "Strings");
/* Define the Lambda expression for the functional interface 'NthBiggest' for
* String data type */
NthBiggestGenerics<String> Nb3 = ((strArr, pos) -> {
Arrays.sort(strArr);
System.out.println("The " + pos + "th largest entity in Array is=" + strArr[strArr.length - pos]);
});
Nb3.NthBig(strArray, 6);
}
}
OUTPUT:
The array of Integers are
[34 21 45 75 62 98 13 49 ]
The 4th largest entity in Array is=49
The array of Doubles are
[34.0 21.0 45.0 75.0 62.0 98.0 13.0 49.0 ]
The 5th largest entity in Array is=45.0
The array of Strings are
[MIKE DAVE JOHN RAMAA SANJAY RUSS NAGENDRA ]
The 6th largest entity in Array is=JOHN

Leave a comment