0% found this document useful (0 votes)
149 views8 pages

Java Stream API - Questions and Answers

The document provides a comprehensive Q&A on the Java Stream API, covering stream creation, operations, reduction, parallel streams, and enhancements in Java 9. It explains various methods for creating streams from collections, arrays, files, and other sources, as well as the behavior of streams and their operations. Additionally, it discusses stream reduction techniques, parallel stream usage, and new features introduced in Java 9.

Uploaded by

kaushik ghosh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
149 views8 pages

Java Stream API - Questions and Answers

The document provides a comprehensive Q&A on the Java Stream API, covering stream creation, operations, reduction, parallel streams, and enhancements in Java 9. It explains various methods for creating streams from collections, arrays, files, and other sources, as well as the behavior of streams and their operations. Additionally, it discusses stream reduction techniques, parallel stream usage, and new features introduced in Java 9.

Uploaded by

kaushik ghosh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Java Stream API - Questions and Answers

Stream Creation
Q1: What method should be used to create an empty stream? A1: The empty() method
should be used to create an empty stream: Stream<String> streamEmpty =
Stream.empty();

Q2: How can you create a stream from a Collection? A2: You can create a stream from any
Collection by calling the stream() method:

Collection<String> collection = Arrays.asList("a", "b", "c");


Stream<String> streamOfCollection = collection.stream();

Q3: How can you create a stream from an array? A3: You can create a stream from an array
using Stream.of() or Arrays.stream():

// Using Stream.of()
Stream<String> streamOfArray = Stream.of("a", "b", "c");

// Using Arrays.stream()
String[] arr = new String[]{"a", "b", "c"};
Stream<String> streamOfArrayFull = Arrays.stream(arr);
Stream<String> streamOfArrayPart = Arrays.stream(arr, 1, 3); // Partial stream from index 1
(inclusive) to 3 (exclusive)

Q4: How do you create an infinite stream using the Stream API? A4: There are two ways to
create an infinite stream:

1.​ Using Stream.generate(): Stream<String> streamGenerated =


Stream.generate(() -> "element").limit(10);
2.​ Using Stream.iterate(): Stream<Integer> streamIterated =
Stream.iterate(40, n -> n + 2).limit(20);

Q5: How can you create a stream of primitives? A5: Java 8 offers special interfaces for
primitive streams: IntStream, LongStream, and DoubleStream:

IntStream intStream = IntStream.range(1, 3);


LongStream longStream = LongStream.rangeClosed(1, 3);
Q6: How can you create a stream from a String? A6: You can create a stream from a String
using the chars() method which returns an IntStream:

IntStream streamOfChars = "abc".chars();

Q7: How can you create a stream from a text file? A7: You can create a stream from a text
file using the Files.lines() method:

Path path = Paths.get("file.txt");


Stream<String> streamOfStrings = Files.lines(path);
Stream<String> streamWithCharset = Files.lines(path, Charset.forName("UTF-8"));

Q8: How can you create a stream using Stream.builder()? A8: You can create a stream
using the builder pattern:

Stream<String> streamBuilder = Stream.<String>builder().add("a").add("b").add("c").build();

Q9: How can you create a stream from a Random object? A9: The Random class provides
methods for generating streams of primitives:

Random random = new Random();


DoubleStream doubleStream = random.doubles(3); // Creates a stream of 3 random doubles

Q10: How can you create a stream by splitting a String? A10: You can create a stream by
splitting a String using a RegEx pattern:

Stream<String> streamOfString = Pattern.compile(", ").splitAsStream("a, b, c");

Stream Operations and Behavior


Q11: Can a stream be reused after calling a terminal operation? A11: No, a stream cannot
be reused after calling a terminal operation. Attempting to do so will trigger an
IllegalStateException.

Q12: What are the three parts needed to perform a sequence of operations on a data
source using streams? A12: The three parts needed are:

1.​ The source (where the stream comes from)


2.​ Intermediate operation(s) (transforms the stream into another stream)
3.​ A terminal operation (produces a result or side-effect)

Q13: What is lazy invocation in the context of Stream API? A13: Lazy invocation means that
intermediate operations are only executed when a terminal operation is called. The operations
are not performed when they're declared but only when necessary for the terminal operation
execution.

Q14: Why is the order of operations important in a stream pipeline? A14: The order of
operations is important for performance. Operations that reduce the size of the stream (like
skip(), filter(), and distinct()) should be placed before operations that apply to each
element to avoid unnecessary processing.

Q15: What is the difference between intermediate and terminal operations? A15:
Intermediate operations (like filter(), map()) transform a stream into another stream and
can be chained together. Terminal operations (like collect(), forEach()) produce a result
or side-effect and end the stream pipeline.

Q16: How does vertical execution work in a stream pipeline? A16: Vertical execution means
the pipeline processes one element completely through all operations before moving to the next
element. This allows for optimization like short-circuiting when a terminal operation doesn't need
all elements.

Q17: What is short-circuiting in Stream operations? A17: Short-circuiting means that some
operations can finish processing without examining all elements. For example, findFirst()
will stop processing once it finds the first matching element.

Q18: Which terminal operations in Stream API are short-circuiting? A18: Short-circuiting
terminal operations include findFirst(), findAny(), anyMatch(), allMatch(), and
noneMatch(). They may terminate processing before examining all elements.

Q19: Which intermediate operations in Stream API are short-circuiting? A19:


Short-circuiting intermediate operations include limit() and skip(). They can produce a
finite stream from a potentially infinite stream.

Q20: What happens if you call an intermediate operation but never call a terminal
operation? A20: If you call intermediate operations but never call a terminal operation, no
processing occurs. Intermediate operations only create a description of the pipeline, but actual
execution only happens when a terminal operation is called.

Stream Reduction
Q21: What are the two main methods for custom stream reduction? A21: The two main
methods for custom stream reduction are:
1.​ reduce() - For combining stream elements into a single result
2.​ collect() - For mutable reduction operations that accumulate elements into a
container

Q22: What are the three parameters that can be passed to the reduce() method? A22:
The three parameters are:

1.​ identity - The initial value for the accumulator or default if stream is empty
2.​ accumulator - A function that specifies the logic for aggregating elements
3.​ combiner - A function that aggregates results of the accumulator (used in parallel
mode)

Q23: How can you convert a stream to a Collection using the collect() method? A23:
You can use the Collectors.toList(), Collectors.toSet() or other collector methods:

List<String> collectorCollection =
productList.stream().map(Product::getName).collect(Collectors.toList());

Q24: How can you group stream elements using the collect() method? A24: You can
group stream elements using Collectors.groupingBy():

Map<Integer, List<Product>> collectorMapOfLists = productList.stream()


.collect(Collectors.groupingBy(Product::getPrice));

Q25: How can you calculate the average of numeric elements in a stream? A25: You can
calculate the average using Collectors.averagingInt(), averagingLong(), or
averagingDouble():

double averagePrice = productList.stream()


.collect(Collectors.averagingInt(Product::getPrice));

Q26: How can you join elements of a stream into a single String? A26: You can join
elements using Collectors.joining():

String listToString = productList.stream().map(Product::getName)


.collect(Collectors.joining(", ", "[", "]"));

Q27: How can you partition stream elements based on a predicate? A27: You can partition
elements using Collectors.partitioningBy():
Map<Boolean, List<Product>> mapPartioned = productList.stream()
.collect(Collectors.partitioningBy(element -> element.getPrice() > 15));

Q28: How can you collect statistical information about numeric elements in a stream?
A28: You can use Collectors.summarizingInt(), summarizingLong(), or
summarizingDouble():

IntSummaryStatistics statistics = productList.stream()


.collect(Collectors.summarizingInt(Product::getPrice));

Q29: How can you perform an additional transformation on a collected result? A29: You
can use Collectors.collectingAndThen():

Set<Product> unmodifiableSet = productList.stream()


.collect(Collectors.collectingAndThen(Collectors.toSet(),
Collections::unmodifiableSet));

Q30: How can you create a custom collector? A30: You can create a custom collector using
Collector.of():

Collector<Product, ?, LinkedList<Product>> toLinkedList =


Collector.of(LinkedList::new, LinkedList::add,
(first, second) -> {
first.addAll(second);
return first;
});

Parallel Streams
Q31: How do you create a parallel stream from a Collection? A31: You can create a parallel
stream from a Collection using the parallelStream() method:

Stream<Product> streamOfCollection = productList.parallelStream();

Q32: How can you check if a stream is parallel? A32: You can check if a stream is parallel
using the isParallel() method:

boolean isParallel = stream.isParallel();


Q33: How can you convert a parallel stream back to a sequential stream? A33: You can
convert a parallel stream back to sequential using the sequential() method:

IntStream intStreamSequential = intStreamParallel.sequential();

Q34: What framework does the Stream API use for parallel execution? A34: The Stream
API uses the ForkJoin framework under the hood to execute operations in parallel.

Q35: Can you assign a custom thread pool to a parallel stream? A35: No, by default, there
is no way to assign a custom thread pool to a parallel stream. The common thread pool is used
automatically.

Q36: When should you avoid using parallel streams? A36: You should avoid using parallel
streams when:

1.​ Performing blocking operations


2.​ Tasks have significantly different execution times
3.​ The data set is very small
4.​ The operations are stateful or have side effects

Q37: When might parallel streams be beneficial? A37: Parallel streams might be beneficial
when:

1.​ Processing a large amount of data


2.​ Operations are CPU-intensive
3.​ Tasks take similar time to execute
4.​ Operations are independent and stateless

Java 9 Stream API Enhancements


Q38: What does the takeWhile() method do in Java 9? A38: The takeWhile() method
collects elements from the start of a stream until a given condition is no longer met. As soon as
an element fails the condition, it stops collecting further elements.

Q39: How does the enhanced iterate() method in Java 9 differ from the Java 8
version? A39: Java 9's enhanced iterate() method allows specifying a stopping condition to
create finite streams, while Java 8's version could only create infinite streams:

// Java 9
Stream.iterate(0, i -> i < 10, i -> i + 1).forEach(System.out::println);
Q40: What is the purpose of the ofNullable() method in Java 9? A40: The
ofNullable() method creates a stream with a single element if the element is non-null, or an
empty stream if the element is null. This simplifies handling potentially null elements without
explicit null checks.

Q41: What does the dropWhile() method do in Java 9? A41: The dropWhile() method
discards elements from the start of a stream as long as they satisfy a given predicate. It stops
dropping elements as soon as one fails the condition, at which point it includes all remaining
elements.

Q42: How does takeWhile() differ from filter()? A42: takeWhile() stops processing
once it encounters an element that doesn't match the predicate, while filter() processes the
entire stream and includes all matching elements regardless of position.

Q43: How does dropWhile() differ from skip()? A43: dropWhile() skips elements
based on a condition until the condition is false, while skip() skips a fixed number of elements
regardless of their values.

Q44: What's the advantage of using ofNullable() over a conditional check? A44:
ofNullable() simplifies code by eliminating the need for ternary expressions or null checks
when creating streams from potentially null sources, making code more readable and concise.

Q45: How would you use the new Stream methods in Java 9 to process a sorted list until
a threshold is met? A45: You can use takeWhile() to process elements from a sorted list
until reaching a threshold:

sortedList.stream()
.takeWhile(element -> element.getValue() < threshold)
.forEach(System.out::println);

Additional Stream Operations


Q46: What is the difference between findFirst() and findAny()? A46: findFirst()
returns the first element in the stream that matches the given criteria, respecting encounter
order. findAny() returns any matching element with no guarantee of which one, potentially
offering better performance in parallel streams.

Q47: What is the difference between anyMatch(), allMatch(), and noneMatch()? A47:

●​ anyMatch() returns true if any elements match the predicate


●​ allMatch() returns true if all elements match the predicate
●​ noneMatch() returns true if no elements match the predicate
Q48: How do you count the number of elements in a stream? A48: You can count elements
using the count() terminal operation:

long count = stream.count();

Q49: How do you find the maximum or minimum element in a stream? A49: You can find
the maximum or minimum using max() or min() with a comparator:

Optional<Product> mostExpensive = productList.stream()


.max(Comparator.comparing(Product::getPrice));

Q50: What happens if you try to perform multiple terminal operations on the same
stream? A50: Attempting to perform multiple terminal operations on the same stream will result
in an IllegalStateException with a message like "stream has already been operated upon
or closed."

You might also like