Thursday, May 16, 2024

Java Stream API 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.

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 ArraylistSystem.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.

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 ananonymous 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.

No comments:

Post a Comment