Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Download 1.52 Mb.
Pdf ko'rish
bet74/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   70   71   72   73   74   75   76   77   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

199.
Predicate: This can be used to test a condition. It returns a
boolean value which indicates whether the condition is true or
false. It accepts an argument of any data type.
Consumer: This can be used to operate on a value. It
accepts an argument of any data type and operates on it. It
returns a void.
Function: This can be used to transform an input value. It
accepts an argument of any data type, transforms it and
returns a result.
Supplier: This can be used to produce a value. It does not
accept any argument, but produces a result of any data type.
Explain the java.util.function.Consumer interface with a
code sample.
Answer:
The java.util.function.Consumer is an built–in functional interface.
It is part of the java.util.function package which is added
by Java 8. It has a method called accept() that accepts an
argument of any data type and operates on it. It does not return
any result. This method needs to be implemented via a lambda
expression. The following code demonstrates this:
Consumer printStr = val–>
System.out.println(val); //Line 1
printStr.accept(“Hello World”); //Line 2
Line 1 creates a Consumer called printStr of String type. It
implements the accept() method via a lambda expression that
simply prints the input String. Line 2 invokes the accept method
with the value “Hello World”. So, this code prints the following
output:


200.



201.
Hello World
Explain the differences between the Supplier and
Consumer interfaces.
Answer:
Both the Supplier and Consumer interfaces are built–in functional
interfaces in the java.util.function package. There are
several differences between the two as follows:
The Supplier interface does not accept an argument, the
Consumer interface accepts an argument of any data type
The Supplier interface produces a return value of any data
type, the Consumer interface does not return any value
The Supplier interface basically produces a value of a
Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   70   71   72   73   74   75   76   77   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling