You are here
Home > java > Core Java >

Java Stream API Interview Questions

Java Stream API Interview QuestionsIf you are a java developer, you should have a solid understanding of Java 8 features, especially in the programming part. According to the observations of various corporate trainers in Java, developers comparatively take much time to understand the Java Stream API concepts. They also recommend that developers need much coding practice on Java Stream API concepts rather than going through theoretical concepts again & again. In this article, we will be doing coding practice in the form of MCQs that are frequently asked in the interviews. Undoubtedly, you must also get benefit in the interviews from these Java Stream API Interview Questions.

So, whether you are a beginner or a professional, solve these Java Stream API Interview Questions to learn or refresh your concepts of Java Stream API before appearing in the interview.

Who can get benefitted from these questions?

1) Job seekers: Java 8 Features has become a must have skill for a Java developer if we leave some of the rarest cases. If you are looking for a job as a Java developer or software engineer, you must be asked about your knowledge of Java stream API and its related concepts during a Java interview. Even at the entry level a company can conduct a written test. Most of the times the written test is in the form of multiple choice questions.

2) Students and learners: If you are studying Java or learning to code, understanding Java Stream API concepts will help you build better applications, reduce time to write the code, and improve your programming skills.

3) Experienced developers: Even if you have been working with Java for years, it’s important to stay up-to-date with the language features and best practices. Java Stream API concepts can help you write more efficient and concise code. Going through these Java Stream API Interview Questions can help you identify areas where you may need to improve your knowledge or skills.

4) Managers and recruiters: If you are responsible for hiring Java developers, understanding Java Stream API concepts can help you evaluate a candidate’s knowledge and expertise. Asking Java Stream API Interview Questions can also help you identify candidates who are up-to-date with the latest technologies and trends in Java development.

In summary, Java Stream API Interview Questions can benefit anyone who wants to improve their understanding of Java Stream API concepts, whether they are job seekers, students, experienced developers, or managers and recruiters.

Java Stream API Interview Questions & Answers (MCQs)

Q#1. What is the output of the following code?

List<Integer> numbers = Arrays.asList(11, 20, 33, 45, 52);
int sum = numbers.stream()
                 .filter(n -> n % 4 == 0)
                 .map(n -> n * 2)
                 .reduce(0, Integer::sum);
System.out.println(sum);
(A) 72
(B) 100
(C) 144
(D) 2052

Ans: C. The code filters out the numbers divisible by 4 (20 and 52), doubles them (40 and 104), and then adds them together (144). The reduce() method starts with an initial value of 0 and applies the Integer::sum function to each element of the stream to compute the final sum of 144.

Q#2. Which of the following methods can be used to convert a stream of strings to a list of integers?

(A) mapToInt(Integer::parseInt)
(B) map(Integer::parseInt)
(C) flatMapToInt(Integer::parseInt)
(D) mapToInt(String::valueOf)

Ans: A. The mapToInt() method is used to convert a stream of objects to an IntStream, which has additional methods for integer-specific operations like summation, max, and min. The Integer::parseInt method is passed as the mapping function to convert each string to an integer.

Q#3. What is the output of the following code?

Stream.of(1, 2, 3)
      .flatMap(n -> Stream.of(n, n * 2))
      .forEach(System.out::print);
(A) 123246
(B) 122436
(C) 123123
(D) 246246

Ans: B. In this case, the function passed to flatMap() creates a new stream with the original integer and the integer multiplied by 2. So, for example, the integer 1 will be mapped to a stream containing 1 and 2, the integer 2 will be mapped to a stream containing 2 and 4, and so on. Finally, the forEach() method is used to print each element in the resulting stream to the console using the method reference System.out::print. The result is the concatenated sequence of integers: 122436.

Q#4.What is the output of the following code?

List<Integer> numbers = Arrays.asList(12, 8, 13, 24, 15);

Optional<Integer> result = numbers.stream()
                                  .filter(n -> n > 25)
                                  .reduce((a, b) -> a + b);
System.out.println(result);
(A) 0 
(B) null
(C) Optional.empty 
(D) Compilation error

Ans: C. The code creates a stream from the numbers list, and uses the filter() operation to filter any numbers that are greater than 25. Since there are no numbers left in the stream after the filter, the reduce() operation has nothing to work with and returns an Optional.empty value.

Q#5. What is the output of the following code?

List<String> words = Arrays.asList("hello", "world");
List<Character> letters = words.stream()
                               .flatMap(s -> Stream.of(s.split("")))
                               .collect(Collectors.toList());
System.out.println(letters);
(A) [hello, world] 
(B) [h, e, l, l, o, w, o, r, l, d]
(C) [h, w, e, o, l, r, l, d, l]
(D) [h, e, llo, w, o, rld]

Ans: B. The flatMap() operation is applied to each String in the stream. The flatMap() method takes a function that returns another stream and flattens the resulting streams into a single stream. In this case, the function passed to flatMap() applies the split() method to each String, which splits the String into an array of its individual characters. Finally, the resulting List of Strings is printed to the console using the System.out.println() method. The result is a List containing each character of the original strings as a separate String element.

Q#6. What is the output of the following code?

IntStream.rangeClosed(1, 10)
         .filter(n -> n % 2 == 0)
         .forEach(System.out::print);
(A) 13579
(B) 246810
(C) 2468
(D) None of the Above

Ans. B. The code generates a stream of integers from 1 to 10 (inclusive), filters out the odd numbers, and then prints the even numbers using the forEach() method.

Q#7. Which of the following is an example of a stateful intermediate operation in Java 8 Stream?

(A) map()
(B) filter()
(C) sorted()
(D) distinct()

Ans: D. The distinct() operation removes duplicates from a stream, but it requires the entire stream to be buffered to ensure that no element is repeated. This makes it a stateful intermediate operation.

Q#8. What is the output of the following code if we try to print the result?

Stream.of("Cognizant", "Infosys", "Amdocs")
      .map(s -> s.length())
      .reduce(0, Integer::sum);
(A) 19
(B) 28
(C) 24
(D) 22

Ans: D. The code maps each string to its length, resulting in a stream of integers [9, 7, 6]. The reduce() method then computes the sum of the integers (22), starting with an initial value of 0.

Q#9. Which of the following methods can be used to convert a stream of integers to a list of strings?

(A) map(String::parseInt)
(B) mapToInt(Integer::parseInt)
(C) map(String::valueOf) 
(D) mapToInt(String::valueOf)

Ans: C. The map() method is used to apply a function to each element of the stream, resulting in a stream of strings. The String::valueOf method is passed as the mapping function to convert each integer to its string representation.

Q#10. What is the output of this code?

Map<String, Integer> ages = new HashMap<>();
  ages.put("Robert", 30);
  ages.put("Mary", 25);
  ages.put("Peterson", 40);
  ages.put("Jinny", 35);

int result = ages.entrySet().stream()
                 .filter(entry -> entry.getValue() > 30)
                 .mapToInt(entry -> entry.getValue())
                 .sum();
System.out.println(result);

(A) 65
(B) 70
(C) 75
(D) 35

Ans: C. The code creates a HashMap of names and ages, and then creates a stream of Map.Entry objects using the entrySet() method. The filter() operation filters out the entries that have a value greater than 30. The mapToInt() operation is then used to convert the resulting entries to their values, and the sum() operation is used to compute the sum of all the values in the stream. The resulting sum is 40 + 35 = 75.

Q#11. Which of the following stream operations is used to generate an infinite stream of elements in Java 8?

(A) stream()
(B) forEach()
(C) generate()
(D) parallelStream()

Ans: C. The generate() method is used to generate an infinite stream of elements. It takes a Supplier as an argument, which produces new values to add to the stream.

Q#12. What is the output of the following code?

Stream.of("java", "javascript", "angular")
      .filter(s -> s.startsWith("b"))
      .findFirst()
      .ifPresent(System.out::println);
(A) java
(B) javascript
(C) angular
(D) Nothing is printed.

Ans: D. The code filters the stream to include only elements that start with the letter “b”, finds the first element of the resulting stream, and prints it using ifPresent(). Since there is no element in the stream which starts with letter “b”, the program will be terminated without printing anything.

Q#13. What is the output of the following code?

 IntStream.range(0, 5)
          .mapToObj(b-> "a" + b)
          .sorted(Comparator.reverseOrder())
          .forEach(System.out::println);
(A) a1a2a3a4
(B) a4a3a2a1a0
(C) 1234
(D) 43210

Ans: B. The code generates a stream of integers from 0 to 4 (exclusive), maps each integer to a string starting with the letter “a”, sorts the resulting strings in reverse order using sorted(), and then prints the strings using forEach().

Q#14. Which of the following stream methods is used to obtain a new stream consisting of the first n elements of the original stream?

(A) skip(n)
(B) limit(n)
(C) filter(n)
(D) map(n)

Ans: B. The limit(n) operation is used to obtain a new stream consisting of the first n elements of the original stream.

Q#15. What is the output of the following code?

Stream.of("java", "python", "react")
      .flatMap(s -> s.chars().boxed())
      .forEach(System.out::print);
(A)  10697118971121211161041111101141019799116
(B)  jprjprjavapyhtonreact
(C)  jpr
(D)  javapythonreact

Ans: A. The code maps each string to a stream of characters, and then flattens the resulting stream of streams into a single stream of boxed integers using flatMap(). The resulting stream will contain the Unicode values of the characters in each string, which are then concatenated together into a single stream.The forEach() method then prints the elements of the stream.

Q#16. Which of the following stream methods is used to obtain a new stream consisting of the elements of the original stream that satisfy a given predicate?

(A) distinct()
(B) sorted()
(C) filter()
(D) map()

Ans: C. The filter() operation is used to obtain a new stream consisting of the elements of the original stream that accepts a specific predicate.

Q#17. Which of the following stream methods is used to combine the elements of the stream into a single result?

(A) reduce()
(B) collect()
(C) peek()
(D) forEach()

Ans: A. The reduce() method is used to combine the elements of the stream into a single result. It takes a binary operator as an argument that is used to combine the elements.

Q#18. What is the output of the following code?

Stream.of("spring", "hibernate", "jdbc")
      .map(s -> s.substring(2, 3))
      .forEach(System.out::print);
(A) pid
(B) pribdb
(C) rbb
(D) The code does not compile.

Ans: C. The code maps each string to a substring consisting of the third character of the each string using map(), and then prints the resulting substrings using forEach().

Q#19. Which of the following stream methods is used to obtain a new stream that contains only the elements of the original stream that are not null?

(A) filterNotNull()
(B) removeNull()
(C) filter()
(D) map()

Ans: C. The filter() operation can be used with a null check to obtain a new stream containing only the elements of the original stream that are not null.

Q#20. What is the output of the following code?

IntStream.rangeClosed(1, 5)
         .map(i -> i * i)
         .skip(2)
         .forEach(System.out::print);
(A) 1491625
(B) 91625
(C) 916
(D) 14916

Ans: B. The code generates a stream of integers from 1 to 5 (inclusive), maps each integer to its square using map() which results into [1,4,9,16,25], skips the first two squares using skip(), and then prints the resulting squares using forEach().

Q#21. What is the output of the following code?

Stream.of("A", "B", "C")
      .flatMap(s -> Stream.of(s, s.toLowerCase()))
      .forEach(System.out::print);
(A) ABCabc
(B) AaBbCc
(C) AbC
(D) The code does not compile.

Ans: B. The code applies flatMap() to each element of the stream, which generates a new stream containing the original element and its lowercase counterpart. The resulting stream of streams is then flattened to a single stream, which is printed using forEach().

Q#22. What is the output of the following code?

List<Integer> numbers = Arrays.asList(5, 4, 3, 2, 1);
int sum = numbers.stream()
                 .reduce(10, (a, b) -> a + b);
System.out.println(sum);
(A) 15
(B) 25
(C) 10
(D) Compilation Error in the code.

Ans: B. The code uses the reduce() operation to sum the integers in the numbers list and assigns the resulting sum to the sum variable. The sum is then printed as 25 because first argument in the reduce() method is already 10.

Q#23. What is the output of the following code?

Stream.of(3, 4, 2, 5, 1)
      .map(i -> i * 2)
      .skip(1)
      .limit(3)
      .forEach(System.out::print);

(A) 8410
(B) 16425
(C) 425
(D) 84102

Ans: A. The code first applies the map() operation to the stream to obtain a new stream of double of the original elements. It then skips the first element using skip() and limits the stream to the next three elements using limit(). Finally, it prints the resulting elements using forEach(). Therefore, the output is 8410.

Q#24. What is the output of the following code snippet?

List<String> words = Arrays.asList("java", "springboot", "angular", "javascript", "springframework");
String result = words.stream()
                     .filter(w -> w.length() > 15)
                     .findFirst()
                     .orElse("none");
System.out.println(result);
(a) none
(b) Washington
(c) New York
(d) An error is thrown 

Ans: A. The code creates a list of strings, and then creates a stream from the list. The stream is filtered to only include strings with a length greater than 15, and the first element of the resulting stream is retrieved using the findFirst() method. If no element is found, the orElse() method returns the string “none”.

Q#25. Which of the following is not a terminal operation in Java Stream API?

(A) reduce()
(B) collect()
(C) filter()
(D) findFirst()

Ans: C. filter() is an intermediate operation in Java Stream API, which is used to filter out elements from a stream based on some condition. It returns a new stream that contains only the elements that satisfy the condition. The terminal operations in Java Stream API are the ones that produce a result or a side effect, such as reduce(), collect(), findFirst(), etc.

Q#26. Which of the following statements about the reduce() operation in Java Stream API is correct?

(A) The reduce() operation can only be used with numerical streams.
(B) The reduce() operation always returns a single value.
(C) The reduce() operation is a terminal operation.
(D) The reduce() operation is an intermediate operation.

Ans: C. The reduce() operation in Java Stream API is a terminal operation that combines the elements of a stream into a single value. It can be used with any type of stream, not just numerical streams. The reduce() operation returns an Optional object that may or may not contain the result, depending on whether the stream was empty or not.

Q#27. What is the output of the following code?

IntStream.range(24, 96)
         .limit(3)
         .mapToObj(Integer::toString)
         .forEach(System.out::print);
(A) 949596
(B) 252627
(C) 242526
(D) 939495

Ans: C. The code generates a stream of integers from 24 to 96 (exclusive), limits the stream to the first 3 elements, maps each integer to a string, and then prints the resulting strings using forEach().

Q#28. What is the output of this code?

List<String> words = Arrays.asList("one", "two", "three", "four", "five");
Map<Integer, List<String>> result = words.stream()
             .collect(Collectors.groupingBy(String::length));
System.out.println(result);
(A) {3=[one, two], 4=[four, five], 5=[three]}
(B) {one=3, two=3, three=5, four=4, five=4}
(C) {3=[one, two], 4=[four, five], 5=[three], null=[]}
(D) Compilation error in the code

Ans: A. The code creates a stream from the words list, and uses the groupingBy() collector from the Collectors class to group the elements of the stream into a Map where the keys are the lengths of the strings, and the values are lists of strings with that length. The resulting Map is printed to the console.

Q#29. What is the output of this code?

List<Integer> numbers = Arrays.asList(15, 24, 33, 12, 19);

Map<Boolean, List<Integer>> result = numbers.stream()
                 .collect(Collectors.partitioningBy(n -> n % 2 == 0));

System.out.println(result);
(A) {even=[24, 12], odd=[15, 33, 19]}
(B) {1=[24, 12], 2=[15, 33, 19]}
(C) {false=[15, 33, 19], true=[24, 12]}
(D) Compilation error in the code

Ans: C. The code creates a stream from the numbers list, and uses the partitioningBy() collector from the Collectors class to partition the elements of the stream into a Map where the keys are booleans representing whether the elements satisfy the given predicate (in this case, whether they are even or odd), and the values are lists of elements that satisfy or don’t satisfy the predicate. The resulting Map is printed to the console.

Q#30. What is the output of this code?

List<String> words = Arrays.asList("java", "typescript", "angular", "javascript", "react");
Set<String> result = words.stream()
                          .flatMap(s -> Arrays.stream(s.split("")))
                          .collect(Collectors.toSet());
System.out.println(result);
(A) [a, c, e, g, a, i, j, l, n, e, p, v, r, s, t, r, u, v, y]
(B) [a, c, e, g, i, j, l, n, p, r, s, t, u, v, y]
(C) [java, typescript, angular, javascript, react] 
(D) [a, y, c, e, g, i, k, j, l, n, p, r, s, t, u, v, y]

Ans: B. The code creates a stream from the words list, and uses the flatMap() operation to transform each word into a stream of its individual characters. The resulting stream of characters is then collected into a Set (no repetition of characters) using the toSet() collector from the Collectors class. The resulting set is printed to the console.

Q#31. What is the output of this code?

List<String> words = Arrays.asList("one", "two", "three", "four", "five");
Map<Integer, String> result = words.stream()
             .collect(Collectors.toMap(String::length, 
                 Function.identity(), (s1, s2) -> s1 + "|" + s2));
System.out.println(result);
(A) {3=one, 4=five, 5=three, 6=four}
(B) {3=one|two, 4=five|four, 5=three}
(C) {3=one, two, 4=five, four, 5=three}
(D) Compilation error

Ans: B. The code creates a stream from the words list, and uses the toMap() collector from the Collectors class to create a map with the length of each word as the key, and the word itself as the value. However, if multiple words have the same length, the toMap() collector uses a merge function to combine the values. In this case, the merge function concatenates the two values.

If you are looking for the complete theoretical concepts of Java Stream API, kindly visit a dedicated article on Stream API in Java 8.

♥ Additionally, you may also attempt MCQs on other topics in Java by visiting our Quizzes section.

Leave a Reply


Top