Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Most Asked Java Stream API Interview Questions
2.1.
1. What programming paradigm does Java 8 belong to?
2.2.
2. Functional Interfaces: What Are They?
2.3.
3. What distinguishes a collection from a stream?
2.4.
4. What is the function map() used for? You use it, why?
2.5.
5. What is the function flatmap() used for? Why do you require it?
2.6.
6. What distinguishes Stream's intermediate and terminal operations?
2.7.
7. By "Stream is lazy," what do you mean?
2.8.
8. What distinguishes a Java functional interface from a conventional interface?
2.9.
9. What distinguishes the findFirst() method from the findAny() method?
2.10.
10. What does "Predicate interface" mean?
2.11.
11. Can an array be converted to a stream? How?
2.12.
12. The parallel Stream is what? How can a List be converted into a parallel stream?
2.13.
13. Why is the Default method necessary for a Java 8 interface?
2.14.
14. A Stream API: What Is It? Why is the Stream API necessary?
2.15.
15. What function does Java 8's limit() method serve?
2.16.
16.Create a Java 8 application to calculate the total of all the numbers in a list.
2.17.
17. What distinguishes findFirst() from findAny() in the Stream object?
2.18.
18. What does Java 8's Nashorn mean?
2.19.
19. To determine the lowest and greatest number in a stream, write a Java 8 program.
2.20.
20. What does Java 8's MetaSpace mean?
2.21.
21. What does the Java 8 StringJoiner Class mean? How can we use the StringJoiner Class to join several Strings?
2.22.
22. What does Java’8 Stream pipelining mean?
2.23.
23. Can one interface extend or inherit from another?
2.24.
24. What do Interfaces' static methods do?
2.25.
25. How does a lambda expression relate to a functional interface? What is a lambda expression in Java?
3.
Conclusion
Last Updated: Jun 12, 2024
Medium

Java Stream API Interview Questions and Answers

Author Riya Bhogra
1 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

Any Java program must use Java arrays and collections. Almost all Java applications employ collections or arrays to analyze data, organize data, summarise data, and extract information from data. However, processing data from collections or arrays, filtering data, putting data into groups, and summarising data are not flawless. You'll wind up creating a lot of loops and complicated code. By offering declarative and functional-style operations to handle data, the Streams API, introduced in Java 8, significantly lowers the lines of code required to process data from collections. Additionally, before Java 8, numerous loops were needed because operations couldn't be chained together to build a pipeline. Stream API interview questions can be very tricky at times. Therefore, for acing the stream API interview questions, you need thorough preparation. Let's now look at some of the commonly asked Java stream API interview questions and answers.


Also Read: Java OOPs Interview Questions

Most Asked Java Stream API Interview Questions

1. What programming paradigm does Java 8 belong to?

Functioning programming language
Logical programming language
Object-oriented programming language
Procedural programming language
 

2. Functional Interfaces: What Are They?

An interface that just has one abstract method is said to be functional. These interfaces are implemented using a Lambda Expression. Therefore to utilize it, you must either develop a new functional interface or use an existing one from Java 8.
"@FunctionalInterface" is the annotation used to create a new Functional Interface.
 

3. What distinguishes a collection from a stream?

A Collection contains its elements, whereas a Stream does not, and this is the primary distinction between the two types of data structures. Unlike other views, Stream operates on a view whose elements are kept in a collection or array, but any changes made to Stream do not affect the original collection.
 

4. What is the function map() used for? You use it, why?

In Java, functional map operations are performed using the map() function. This indicates that it can apply a function to change one type of object into another.
Use map(), for instance, to change a List of String into a List of Integers if you have one already.
It will apply to all elements of the List and give you a List of Integer if you only supply a function to convert String to Integer, such as parseInt() or map(). The map can change one object into another.
 

5. What is the function flatmap() used for? Why do you require it?

The map function has been expanded with the flatmap function. It can flatten an object in addition to changing it into another.
If you already have a list of lists but wish to integrate them all into a single list, for instance. You can flatten using flatMap() in this situation. The map() function can be used to transform an object at the same time.
 

6. What distinguishes Stream's intermediate and terminal operations?

You can call additional methods of the Stream class to build a pipeline because the intermediary Stream action returns another Stream.
For instance, you can still call the filter() method on a Stream after calling map() or flatMap().
The terminal action, on the other hand, generates results other than streams, such as a value or a Collection.
You cannot call any other Stream methods or reuse the Stream once a terminal method like forEach() or collect() has been called.

Stream's intermediate and terminal operations

 

7. By "Stream is lazy," what do you mean?

When we state that a stream is lazy, we mean that the majority of its methods, which are described in the Java.util. Stream.Stream classes, will not function if they are simply added to the stream pipeline.
They only function when a terminal method on the Stream is called, and rather than searching through the entire collection of data, and they stop as soon as they locate the data they are looking for.
 

8. What distinguishes a Java functional interface from a conventional interface?

While the functional interface in Java can only contain one abstract method, the normal interface can contain any number of abstract methods.

They wrap a function in an interface, which is why they are termed functional interfaces. The one abstract method on the interface serves as the function's representation.
 

9. What distinguishes the findFirst() method from the findAny() method?

The findAny() function will return any element fitting the criterion, which is particularly helpful when working with a parallel stream. In contrast, the findFirst() method will return the first element meeting the condition, i.e., Predicate. 
 

10. What does "Predicate interface" mean?

A function that takes an Object and returns a boolean is represented by a Predicate, a functional interface. Several Stream methods, like filter(), which employs Predicate to filter out undesirable components, use it.

Here is an example of a predicate function:

public boolean test(T object){
   return boolean; 
}

 

11. Can an array be converted to a stream? How?

Yes, you can use Java to transform an array into a stream. The Stream class offers a factory method to make a Stream from an array, such as Stream.of(T...), which accepts a variable parameter, meaning you may also supply an array to it, as demonstrated in the example below:

String[] languages = {"Java", "Python", "JavaScript"}; 
Stream numbers = Stream.of(languages); 
numbers.forEach(System.out::println); 

 

Output: 

  • Java
  • Python 
  • JavaScript
     

12. The parallel Stream is what? How can a List be converted into a parallel stream?

Stream processing tasks can be carried out in parallel using a parallel stream. A filter can help you find orders worth more than $1 million, for instance, if you have a parallel stream of 1 million orders.

The parallel Stream, as opposed to the sequential Stream, can start numerous threads to look for such orders on various parts of the Stream, then combine the results.
 

13. Why is the Default method necessary for a Java 8 interface?

The default method was crucial to Java 8's success because it allowed the API designer to incorporate new methods into already-existing interfaces without causing any classes to break that implement Collection, Iterable, Map, List, and other well-liked interfaces to become obsolete.

The forEach() method is a nice illustration of the requirement for the default method because, without it, it would not be possible to specify the method in Iterable and make it immediately available to all Collection classes.
 

14. A Stream API: What Is It? Why is the Stream API necessary?

Java 8 now has a new functionality called Stream API. Stream API is a unique class used for handling items from sources like collections.

The Stream API is required because: 

  • Processing is straightforward since it offers aggregate operations.
  • Programming in the functional style is supported.
  • The processing speed is accelerated. It is, therefore, suitable for greater performance.
  • Parallel operations are possible.
     

15. What function does Java 8's limit() method serve?

The limit of the elements is specified via the Stream.limit() function. Limit(X) returns a Stream with the specified size, where X is the value you entered. It belongs to the class java.util. Stream.Stream.

Syntax :

limit(x)

 

*where "X" denotes the element's size.
 

16.Create a Java 8 application to calculate the total of all the numbers in a list.

To store the components in our application, we have utilized an ArrayList. The sum of all the entries in the ArrayList was then determined using the sum() method. Then, using the mapToInt() and sum() methods, it is turned into a stream, and each element is added.

import java.util.*;
class Java8 {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>();
 
        list.add(10);
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);
        // Added the numbers into Arraylist
        System.out.println(sum(list));
    }
 
    public static int sum(ArrayList<Integer> list) {
        return list.stream().mapToInt(i -> i).sum();
        // Found the total using sum() method after
        // converting it into Stream
    }
}

 

17. What distinguishes findFirst() from findAny() in the Stream object?

The findAny() method is used to find any element from the Stream, but the findFirst() method is used to discover the first element from the Stream, as the name implies.

While the findAny() is non-deterministic, the findFirst() is predestinarian in nature. Deterministic programming refers to a system where the outcome is determined by the input or beginning state.
 

18. What does Java 8's Nashorn mean?

A Java-based engine for running and analyzing JavaScript code is called Nashorn in Java 8.
 

19. To determine the lowest and greatest number in a stream, write a Java 8 program.

To obtain the highest and lowest integer from a Stream in this application, we used the min() and max() functions. First, with the aid of the Comparator, we initialized a stream that contains integers. We have compared the components of the Stream using the comparing() function.

The highest and lowest integers will be returned when this function is combined with max() and min(). When comparing the Strings, it will also function.

import java.util.Comparator;
import java.util.stream.*;
 
public class Java8{
   public static void main(String args[]) {
         
    Integer highest = Stream.of(1, 2, 3, 77, 6, 5)
                        .max(Comparator.comparing(Integer::valueOf))
                        .get();
     
    /* We have used max() method with Comparator.comparing() method
       to compare and find the highest number
    */
          
    Integer lowest = Stream.of(1, 2, 3, 77, 6, 5)
                        .min(Comparator.comparing(Integer::valueOf))
                        .get();
     
    /* We have used max() method with Comparator.comparing() method
       to compare and find the highest number
    */
     
    System.out.println("The highest number is: " + highest);
    System.out.println("The lowest number is: " + lowest);
   }
}

 

20. What does Java 8's MetaSpace mean?

A new feature to store classes was added in Java 8. In Java 8, there is a place called MetaSpace where all the classes are kept. The PermGen has been superseded by MetaSpace.

The Java Virtual Machine used PermGen to store the classes before Java 7. Java 8 replaced PermGen with MetaSpace because MetaSpace is dynamic and has no size restrictions. It can also increase dynamically.

Click here to know about, System Design Interview Questions
 

21. What does the Java 8 StringJoiner Class mean? How can we use the StringJoiner Class to join several Strings?

StringJoiner is a new class that was added to the java.util package in Java 8. With the help of this class, we may combine numerous strings that have been separated by delimiters and add prefixes and suffixes to them.

Using the StringJoiner Class, we will learn how to join several Strings in the program below. The delimiter between the two strings in this instance is ",". After that, we combined five distinct strings by adding them together using the add() method. The String Joiner was then printed.

import java.util.StringJoiner;
 
public class Java8 {
    public static void main(String[] args) {
 
        StringJoiner stj = new StringJoiner(",");
        // Separated the elements with a comma in between.
         
        stj.add("Saket");
        stj.add("John");
        stj.add("Franklin");
        stj.add("Ricky");
        stj.add("Trevor");
         
        // Added elements into StringJoiner “stj”
         
        System.out.println(stj);
    }
}

 

22. What does Java’8 Stream pipelining mean?

Chaining together operations is the idea behind Stream pipelining. To do this, we divide the possible operations on a stream into two groups: intermediate operations and terminal operations.

When an intermediate action completes, it produces an instance of Stream. As a result, we can create a processing pipeline with any number of intermediary processes to process data.

The pipeline must then be terminated by a terminal operation that returns a final value.
 

23. Can one interface extend or inherit from another?

Because it would violate the restriction of one abstract method per functional interface, a functional interface cannot extend another interface with abstract methods.

interface Parent { 
public int parentMethod(); 
} 
@FunctionalInterface // This cannot be FunctionalInterface 
interface Child extends Parent { 
public int childMethod(); 
// It will also extend the abstract method of the Parent Interface 
// Hence it will have more than one abstract method 
// And will give a compiler error 
}


It can extend other interfaces that only have the standard, default, static, and overridden by other class methods and lack any abstract methods.

interface Parent { 
public void parentMethod(){ 
System.out.println("Hello"); 
} 
} 
@FunctionalInterface 
interface Child extends Parent { 
public int childMethod(); 
}

24. What do Interfaces' static methods do?

 Static methods, which contain method implementation and are invoked using the interface's name, are excellent for defining utility methods because they are owned by the interface and cannot be overridden.
 

25. How does a lambda expression relate to a functional interface? What is a lambda expression in Java?

A function type without a name is a lambda expression. Results and parameters may or may not be present. Since it lacks type information, it is referred to as an anonymous function. It is carried out as needed. It helps with data extraction, filtering, and iteration from collections.

Lambda expressions can only be used with the single abstract method of the Functional Interface since they are equivalent to anonymous functions. From the signature of the abstract method of the functional interface, it will deduce the return type, type, and several parameters.
 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Conclusion

In this article, we have extensively discussed some commonly asked Stream API Interview Questions. We hope this blog has helped you enhance your knowledge regarding the same and you'll be able to answer all your stream API interview questions from now on.

Recommended Readings:

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! 

Happy Learning!

Previous article
Spring Interview Questions and Answers (2023)
Next article
Struts Interview Questions
Live masterclass