Mastering Java Streams: Practice Questions and Answers
Java Streams are a powerful tool for modern developers, enabling concise and efficient data processing. Below is a curated list of questions and answers, ranging from beginner to expert level, to help you strengthen your understanding of Java Streams.
Beginner-Level Questions
1. What is a Stream in Java? How is it different from a Collection?
A Stream is a sequence of elements that supports aggregate operations like filtering, mapping, and reducing. Unlike Collections, Streams are not data structures; they don’t store elements but process them on demand. Streams are also lazy, meaning computation happens only when required.
2. How do you create a Stream from a List
, Set
, or an Array
?
// From a List
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> streamFromList = list.stream();
// From a Set
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));
Stream<Integer> streamFromSet = set.stream();
// From an Array
String[] array = {"x", "y", "z"};
Stream<String> streamFromArray = Arrays.stream(array);
3. Write a program to filter out all even numbers from a List
using Streams.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers); // Output: [2, 4]
4. What is the difference between map()
and filter()
in Streams?
map()
is used to transform each element in a Stream, while filter()
is used to retain elements that satisfy a condition.
// Example of map()
List<String> names = Arrays.asList("john", "jane");
List<String> upperNames = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
// Output: [JOHN, JANE]
// Example of filter()
List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
// Output: [2, 4]
5. How can you collect the elements of a Stream into a List
or a Set
?
Use the Collectors.toList()
or Collectors.toSet()
methods:
List<String> list = stream.collect(Collectors.toList());
Set<String> set = stream.collect(Collectors.toSet());
Intermediate-Level Questions
1. What is the difference between Stream.of()
and Arrays.stream()
?
Stream.of()
creates a Stream from individual values or arrays. Arrays.stream()
works only with arrays.
// Stream.of()
Stream<String> stream1 = Stream.of("a", "b", "c");
// Arrays.stream()
String[] array = {"x", "y", "z"};
Stream<String> stream2 = Arrays.stream(array);
2. Write a program to find the first element of a Stream using findFirst()
.
List<Integer> numbers = Arrays.asList(10, 20, 30);
Optional<Integer> firstNumber = numbers.stream().findFirst();
System.out.println(firstNumber.get()); // Output: 10
3. How do you find the maximum and minimum value in a Stream of integers?
List<Integer> numbers = Arrays.asList(3, 7, 1, 9, 5);
int max = numbers.stream().max(Integer::compareTo).get();
int min = numbers.stream().min(Integer::compareTo).get();
System.out.println("Max: " + max); // Output: Max: 9
System.out.println("Min: " + min); // Output: Min: 1
4. Write a program to concatenate two Streams.
Stream<String> stream1 = Stream.of("a", "b");
Stream<String> stream2 = Stream.of("c", "d");
Stream<String> concatenatedStream = Stream.concat(stream1, stream2);
concatenatedStream.forEach(System.out::println);
// Output: a b c d
Expert-Level Questions
1. Write a program to compute the frequency of each word in a list of strings using Streams.
List<String> words = Arrays.asList("apple", "banana", "apple", "orange", "banana", "apple");
Map<String, Long> frequency = words.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(frequency);
// Output: {orange=1, banana=2, apple=3}
2. Explain the purpose of flatMap()
. Provide an example of flattening a list of lists into a single list.
flatMap()
is used to transform and flatten streams of collections into a single Stream.
List<List<Integer>> listOfLists = Arrays.asList(
Arrays.asList(1, 2, 3),
Arrays.asList(4, 5, 6)
);
List<Integer> flattenedList = listOfLists.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println(flattenedList); // Output: [1, 2, 3, 4, 5, 6]
3. Write a program to partition a list of integers into even and odd numbers using Collectors.partitioningBy()
.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
Map<Boolean, List<Integer>> partitioned = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println("Even: " + partitioned.get(true)); // Output: [2, 4, 6]
System.out.println("Odd: " + partitioned.get(false)); // Output: [1, 3, 5]
Conclusion
This comprehensive guide provides answers to a wide range of Java Streams questions, helping you build your expertise from beginner to advanced levels. Practice these examples, and you'll be well-prepared for both interviews and real-world projects!
No comments:
Post a Comment