Java 8 features: Lambda Expressions Streams Functional Interfaces Method References Default Methods Optional New Date and Time API (java.time) Collection Enhancements 1. Lambda Expressions What? Lambda expressions in Java allow you to define and use small, anonymous functions. They simplify the way you write code by providing a more concise syntax for defining methods, particularly in functional interfaces. Why? Lambda expressions make your code shorter and more readable by reducing boilerplate code. They are particularly useful when working with functional interfaces like Runnable and Callable . Pre-Java 8 Example: Before Java 8, you'd typically use anonymous inner classes for similar functionality. For instance, a Runnable could be defined as follows: Runnable runnable = new Runnable () { public void run () { System.out.println( "Hello from Runnable!" ); } }; Java 8 Example: With lambda expressions, the same can be achieved with a much cle...
To find the second-highest salary from a list of employees using Java 8 streams, you can follow these steps: Create a list of employees with their salaries. Use Java 8 streams to sort the employees by salary in descending order. Skip the first element (which is the employee with the highest salary). Get the first element of the remaining stream (which is the employee with the second-highest salary). Example code: java import java.util.ArrayList; import java.util.List; class Employee { private String name; private double salary; public Employee (String name, double salary) { this .name = name; this .salary = salary; } public double getSalary () { return salary; } } public class SecondHighestSalary { public static void main (String[] args) { List<Employee> employees = new ArrayList <>(); employees.add( new Employee ( "John" , 60000.0 )); employees.add( new Employe...