To find the largest number in a list in Java, you can use the stream()
method to create a stream of the list, and then use the max()
method to find the maximum value.
Here's an example of how to do it:
import java.util.Arrays; import java.util.List; import java.util.OptionalInt; public class Main { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Find the largest number in the list OptionalInt max = list.stream() .mapToInt(Integer::intValue) .max(); if (max.isPresent()) { System.out.println(max.getAsInt()); // prints "10" } } }
This code creates a list of integers and then uses the mapToInt()
method to convert the elements to int
values and the max()
method to find the maximum value. The isPresent()
method is used to check if a maximum value was found, and the getAsInt()
method is used to retrieve the value.