Java 8 Program to Find the Smallest 3 Numbers from a List

Learn Java 8 Program to Find the Smallest 3 Numbers from a List using Stream API, sorted(), and limit() methods with examples.

Code Explanation point wise

  • Arrays.asList() method creates a list of integer values.
  • list.stream() converts the list into a stream for processing data.
  • sorted() method sorts all numbers in ascending order.
  • limit(3) method retrieves only the first three elements from the sorted stream.
  • collect(Collectors.toList()) method converts the stream back into a List.
  • Now the smallest three numbers are printed.
				
					import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MinThreeNumber {
    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(12, 43, 56, 37, 98, 25, 80);

        List<Integer> minNumber = list.stream()
                                      .sorted()
                                      .limit(3)
                                      .collect(Collectors.toList());

        System.out.println("Smallest three number are :- " + minNumber);
    }
}
				
			

Output :
Smallest three number are :- [12, 25, 37]

How to Find Minimum 3 Values from a List in Java 8 Using Stream API

				
					import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MinThreeValues {
    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(12, 43, 56, 37, 98, 25, 80);

        List<Integer> minThree = list.stream()
                                     .sorted()
                                     .collect(Collectors.toList())
                                     .subList(0, 3);

        System.out.println("Minimum three values are : " + minThree);
    }
}
				
			

FAQ
How do I find the smallest 3 numbers in Java 8?
Use sorted() to sort the stream and limit(3) to retrieve the first three smallest values.
What does limit(3) do in Java Stream?
It restricts the stream to only the first three elements.
Is sorted() ascending by default?
Yes, sorted() sorts elements in natural ascending order.
Which Stream methods are used to find minimum values?
Common methods include:
sorted()
limit()
min()
collect()
Can I find the top 5 minimum values using the same approach?
list.stream().sorted().limit(5).collect(Collectors.toList());