Java stream interview questions: Part 2

Mukul Jha
Towards Dev
Published in
3 min readSep 21, 2024

Q. How do you create an infinite stream of random numbers using a stream?

Random random = new Random();
Stream<Integer> stream = Stream.generate(random::nextInt);
stream.forEach(data -> System.out.println(data));

Output: Infinite stream of random integers

Q. How do you handle null values in streams?

List<String> footballers = Arrays.asList("Kylian Mbappe", null, "Erling Haaland", null, null, "Pedri", "Vinicius Junio");

footballers = footballers.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());

System.out.println(footballers);

Output: [Kylian Mbappe, Erling Haaland, Pedri, Vinicius Junio]

Q. Find all non-duplicate integers using streams.

List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 3, 1, 5, 6);
List<Integer> nonDuplicates = numbers.stream()
.collect(Collectors.groupingBy(num -> num, Collectors.counting()))
.entrySet().stream()

// Filter nums with occurrence(count) == 1 (non-duplicates)
.filter(entry -> entry.getValue() == 1)
.map(Map.Entry::getKey)
.toList();

System.out.println(nonDuplicates);

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

No responses yet

What are your thoughts?