FAQs on Java Streams and Lambda Expressions
1.What is Java Streams and how does it work?
Answer: Java Streams In Java 8, the developers introduce a new modern way to process sequences of elements in a functional style. A stream is an operation that lets you process data as a pipeline of operations which is executed lazily, meaning that nothing is done unless a terminal operation is invoked collect(), forEach(), reduce() etc. It does not change the original data structure; it returns a new result.
Streams are built to handle huge datasets efficiently and can also be processed in parallel to take advantage of multi-core processors.
Example:
import java.util.Arrays;
import java.util.List;
public class StreamExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
. sum();
System.out.println("Sum of even numbers: " + sum);
}
}
In the example above, we first filter the even numbers and then sum them up. The stream() starts the stream, and the terminal operations such as filter() and sum() are done.
2.Explain the differences between intermediate and terminal operations of Streams.
Answer: In Java Streams, the operations are classified into intermediate and terminal operations.
• Intermediate operations are lazy and do not perform execution until the terminal operation is called. It returns a new stream and thus allows chaining.
Examples include filter(), map(), sorted(), and distinct().
•It is the operations at the terminal that actually run the stream pipeline. They emit a result or side-effect, and they never return a stream. Some examples of terminal operations are collect(), forEach(), reduce(), and count().
Example
import java.util.Arrays;
import java.util.List;
public class StreamOperationsExample {
public static void main(String[] args)
{
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
long count = numbers.stream().
filter(n -> n % 2 == 0); // intermediate
.count(); // terminal
System.out.println("Number of even numbers: " + count);
}
}
In the example, filter() is an intermediate operation and count() is a terminal operation.
3.What are Lambda Expressions and how are they used with Streams?
Answer: A Lambda Expression is a short block of code that takes in parameters and returns a value. It's a function that can be passed around and executed later. Lambdas simplify the syntax and allow you to write more concise code.
When combined with Streams, Lambdas are used to define the behavior of stream operations, such as filtering, mapping and reducing elements in a collection.
Example:
import java.util.Arrays;
import java.util.List;
public class LambdaExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry");
words.stream()
.filter(word -> word.startsWith("b"))
.forEach(System.out::println); // prints "banana"
}
}
In this example, the Lambda expression word -> word.startsWith("b") filters words that start with "b", and forEach() prints them.
4.What are functional interfaces? Illustrate them with Streams.
Answer: Functional Interface is the interface having single abstract method or SAM. These are used for representation of behaviour which is passed on to the methods or lambda expressions. They are predicates, Functions, Consumers and Supplier etc.
In streams, the most of these are used as parameter in a number of methods which includes filter(), map() and foreach().
Example
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class FunctionalInterfaceExample
public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Alice", "Bob");
Predicate<String> startsWithB = name -> name.startsWith("B");
names.stream()
.filter(startsWithB)
.forEach(System.out::println); // prints "Bob"
}
}
Here, Predicate<String> is a functional interface used to filter strings starting with "B".
5.What is the map() function in Streams?
Answer: A map() function in Java Streams carries out the conversion of every element located in the stream to another form. Here, it uses a given function to apply elements and delivers new streams containing the converted elements. This is pretty helpful when the elements in any collection are to be converted or altered.
Example.
import java.util.Arrays;
import java.util.List;
public class MapExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
List<Integer> doubled = numbers.stream()
.map(x -> x * 2)
.toList();
System.out.println(doubled); // prints [2, 4, 6, 8]
}
}
In this example, map() is used to double each number in the list.
6.Describe the filter() method in Streams.
Answer: The filter() method in Java Streams is used to choose elements from a stream that meet a specified condition. It accepts a Predicate (a functional interface) as an argument, which returns a boolean value.
The filter() method is a middle operation and it does not modify the source collection but produces a new stream with elements passing the predicate.
Example:
import java.util.Arrays;
import java.util.List;
public class FilterExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.toList();
System.out.println(evenNumbers); // prints [2, 4]
}
}
The filter() method filters the stream to contain only even numbers.
7.How dose Integer wrapper class help in java?
Answer: The reduce() operation in Streams is a terminal operation that aggregates elements of a stream into a single result by repeatedly applying a binary operator. It is used very often to do aggregate operations such as sum, multiplication or finding the minimum/maximum.
Example:
import java.util.Arrays;
import java.util.List;
public class ReduceExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
System.out.println("Sum: " + sum); // prints 15
}
}
In this example, reduce() sums up all the elements in the list.