Java 8 -Streams API Few Questions


1. Given a list of strings, print them in uppercase in alphabetical order.
Explanation: Map each string to uppercase, then sort and print.
Solution (Java):
list.stream()
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);

2. Given a list of strings, print them in uppercase by the length of each element.
Explanation: Map to uppercase, then sort by length using Comparator.comparingInt.
Solution (Java):
list.stream()
.map(String::toUpperCase)
.sorted(Comparator.comparingInt(String::length))
.forEach(System.out::println);

3. Given a list of strings, remove null or empty strings from the list.
Explanation: Filter out nulls and empty values, collect to a list.
Solution (Java):
List cleaned = list.stream()
.filter(s -> s != null && !s.isEmpty())
.collect(Collectors.toList());

4. Given a list of nums, square each number in the list.
Explanation: Map each number to its square.
Solution (Java):
List squared = nums.stream()
.map(n -> n * n)
.collect(Collectors.toList());

5. Given a list of nums, find the largest number in the list.
Explanation: Use max with natural ordering.
Solution (Java):
Optional max = nums.stream().max(Integer::compareTo);
int largest = max.orElseThrow(() -> new NoSuchElementException(“List empty”));



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *