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


Download 1.52 Mb.
Pdf ko'rish
bet97/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   93   94   95   96   97   98   99   100   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

252.
CHAPTER
08
Collection Improvements
Explain with a code sample how the forEach method
works.
Answer:
Java 8 has added a new default method called forEach to the
Iterable interface. The java.util.Collection interface
extends the Iterable interface and so the forEach method is
available to all the Collection classes. The forEach method
helps to internally iterate through a Collection without an explicit
for loop. The following code demonstrates this:
List colours =
Arrays.asList(“Red”,”Blue”,”Black”,”White”);
colours.forEach(str–> System.out.println(str));
This code declares a List of String values called colours. The
forEach() method is then invoked on this List. The forEach()
method accepts as parameter a Consumer instance and
operates on it. In this case, the Consumer is implemented via a
lambda expression that simply prints the value passed to it. So,
this code prints the following output:
Red
Blue
Black
White


253.
a.
b.
254.
What are some of the improvements made by Java 8 on
the List interface?
Answer:
Java 8 has added some methods to the List interface as follows:
List.sort: Java 8 has added the List.sort method. This
can be used to sort a List. It accepts as parameter a
Comparator and sorts the input List as per the specified
Comparator.
List.replaceAll: Java 8 has added the
List.replaceAll method. This can be used to replace all
the values in a List. It accepts as parameter a
UnaryOperator interface. UnaryOperator is a
specialization of the Function interface that accepts an
input of a particular data type and returns a result of the
same data type. The replaceAll() method applies the
UnaryOperator to each element in the List.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   93   94   95   96   97   98   99   100   ...   171




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