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


Is it possible to convert an array to a Stream? Explain


Download 1.52 Mb.
Pdf ko'rish
bet85/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   81   82   83   84   85   86   87   88   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

Is it possible to convert an array to a Stream? Explain.
Answer:
Yes, it is possible to convert an Array to a Stream. Java 8 has
added a stream() method to the java.util.Arrays class.
This has many overloaded versions that accept arrays of different
data types and convert the array to a Stream. The following code
demonstrates converting an Integer array to a Stream:
int[] numbers = {10,20,30};
IntStream numberStream = Arrays.stream(numbers);


226.
This code first creates an int array called numbers. It then uses
the Arrays.stream method passing it the input array. The
Arrays.Stream method returns an IntStream which is a
primitive specialization of the Stream interface. Just like
IntStream, Java 8 has also added DoubleStream and
LongStream which are returned when the Arrays.stream
method is invoked with a double or long array respectively.
Suppose you have an Employee class as follows:
public class Employee {
private String name;
private int salary;
}
And suppose you have a List of Employee objects as
follows:
List employees = new ArrayList();
employees.add(new Employee(“John”,10000));
employees.add(new Employee(“Ana”,15000));
employees.add(new Employee(“Tia”,8000));
How can you create a new List is sorted based on the
Employee salary using Streams?
Answer:
The following code can be used to create a new List sorted
based on the Employee salary:
List sortedList =
employees.stream().sorted((emp1, emp2)–>


emp1.getSalary()–
emp2.getSalary()).collect(Collectors.toList());
sortedList.forEach(emp–>
System.out.println(emp.getSalary()));
This code first obtains a Stream on the employees List. It then
invokes the sorted() operation. The sorted() method
accepts as input a Comparator. Here, the Comparator is
implemented via a lambda expression that compares the salary
fields of the Employee objects. Finally, the collect() method
is invoked to convert the Stream back to a List. So, this code
prints the following output:
8000
10000
15000
20000




Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   81   82   83   84   85   86   87   88   ...   171




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