Posts

Showing posts with the label Finding largest & smallest element in an Array

Java 8 Streams - Finding largest & smallest element in an Array, List & Set

Example 1: Finding the largest element in an array import java.util.Arrays; /* Java Program to find the largest number from an Array. */ public class DriverClass { public static void main( String [] args) { int [] numbers = { 2 , 6 , 7 , 9 , 5 , 155 , 66 , 99 }; int largestNumber = Arrays.stream(numbers). max().getAsInt(); System.out.println( "Largest Number= " + largestNumber); } } Output: Largest Number= 155 Example 2: Finding the largest element in a List import java.util.Arrays; import java.util.Comparator; import java.util.List; /* Java Program to find the largest number from a List. */ public class DriverClass { public static void main( String [] args) { List < Integer > numbers = Arrays. asList( 2 , 6 , 7 , 9 , 5 , 155 , 66 , 99 ); int largestNumber = numbers.stream(). max(Comparator.comparing