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