Java.Java8.How can I display 10 random numbers in ascending order?

👌 To display 10 random numbers in ascending order, you can:

  1. Generate 10 random numbers,
  2. Sort them using sorted(),
  3. Print them using forEach().

✅ Example Using Random and Streams

import java.util.Random;
import java.util.stream.Stream;

public class SortedRandomNumbers {
    public static void main(String[] args) {
        Random random = new Random();

        Stream.generate(() -> random.nextInt(100)) // random numbers 0–99
              .limit(10)                           // get 10 numbers
              .sorted()                            // sort them
              .forEach(System.out::println);       // print
    }
}

🔹 Sample Output:

4
15
21
34
45
48
56
70
85
97

✅ Summary of Methods Used:

MethodPurpose
Stream.generate()Infinite stream of random numbers
limit(10)Get first 10 elements
sorted()Sorts numbers in natural (ascending) order
forEach()Prints each number
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.