You can use Java 8 Streams to get the three maximum and three minimum numbers from a given list of integers by using sorted()
, limit()
, and distinct()
if needed.
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class ThreeMaxThreeMin { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(10, 5, 30, 25, 100, 50, 70, 1); // Get three minimum numbers List<Integer> minNumbers = numbers.stream() .sorted() // Sort in ascending order .limit(3) // Take the first 3 elements .collect(Collectors.toList()); // Get three maximum numbers List<Integer> maxNumbers = numbers.stream() .sorted((a, b) -> b - a) // Sort in descending order .limit(3) // Take the first 3 elements .collect(Collectors.toList()); System.out.println("Three Minimum Numbers: " + minNumbers); System.out.println("Three Maximum Numbers: " + maxNumbers); } }
Output:
Three Minimum Numbers: [1, 5, 10] Three Maximum Numbers: [100, 70, 50]
Explanation:
- Sorting the list:
sorted()
→ Sorts the list in ascending order (for min numbers).sorted((a, b) -> b - a)
→ Sorts in descending order (for max numbers).
- Extracting top 3:
limit(3)
→ Takes the first 3 elements from the sorted list.
- Collecting results:
.collect(Collectors.toList())
→ Converts the stream back into a list.
Handling Duplicates
If you want unique numbers, use distinct()
before sorting:
numbers.stream().distinct().sorted().limit(3).collect(Collectors.toList());