To get the smallest number in a list or array of numbers in Java, you can use the min()
method of the Collections
class. This method returns the minimum element of the list, according to the natural ordering of the elements.
Here's an example of how you could use the min()
method to get the smallest number in a list:
import java.util.Arrays; import java.util.Collections; import java.util.List; List<Integer> numbers = Arrays.asList(5, 3, 8, 1, 9, 4, 2, 7, 6); int smallestNumber = Collections.min(numbers); System.out.println("Smallest number: " + smallestNumber);
This code will output "Smallest number: 1", because 1 is the smallest number in the list.
You can also use the min()
method to get the smallest number in an array by first converting the array to a list using the asList()
method of the Arrays
class. For example:
int[] numbers = {5, 3, 8, 1, 9, 4, 2, 7, 6}; int smallestNumber = Collections.min(Arrays.asList(numbers)); System.out.println("Smallest number: " + smallestNumber);
This code will produce the same output as the previous example.
Note that the min()
method requires the elements of the list or array to be comparable, meaning that they must implement the Comparable
interface and have a natural ordering. If the elements are not comparable, the method will throw a ClassCastException
. In that case, you can use a custom comparator to compare the elements and find the smallest number.