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


Download 1.52 Mb.
Pdf ko'rish
bet101/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   97   98   99   100   101   102   103   104   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

needs to be done to fix it.
public class Employee {
private String name;
private double salary;
//constructor, getters and setters
}
List employees = new ArrayList();
employees.add(new Employee(“A”,10000));
employees.add(new Employee(“B”,5000.50));
employees.add(new Employee(“C”,15000));
employees.sort(Comparator.comparingInt(employee–>
employee.getSalary())); //Line 1
Answer:
The above code has a compilation error at Line 1. The
employees.sort() method is used with the
Comparator.comparingInt. This method accepts as
parameter a ToIntFunction functional interface and sorts
based on an int field. However, here a lambda expression that


261.



returns the salary value which is a double is used. So, this
causes a compilation error. In order to fix this error, Line 1 needs
to be modified as follows:
employees.sort(Comparator.comparingDouble(employee–>
employee.getSalary()));
Now, the Comparator.comparingDouble() method is used.
This method accepts as parameter a ToDoubleFunction
interface that compares based on a Double field.
Explain the differences between the
CompletableFuture.runAsync and the
CompletableFuture.supplyAsync methods.
Answer:
Both the runAsync and the supplyAsync methods can be
used to run code asynchronously. However, there are some
differences between the two as follows:
The runAsync method does not return a result, so it returns
a CompletableFuture. The supplyAsync method
on the other hand returns a value from the thread. So, it
returns a CompletableFuture.
The runAsync method accepts as parameter a Runnable
instance. The supplyAsync method on the other hand
accepts as parameter a Supplier instance.
The runAsync method executes the code in the Runnable
implementation in a separate thread. The supplyAsync
method on the other hand executes the code in the
Supplier in a separate Thread and returns the value
produced by the Supplier.




Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   97   98   99   100   101   102   103   104   ...   171




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