Data Structures and Algorithms in Java Understanding Data Structures ArrayList When to Use: Use ArrayList when you need a dynamic array that can grow or shrink in size. It's efficient for random access but less efficient for frequent insertions and deletions. Example Code: java List<String> arrayList = new ArrayList <>(); arrayList.add( "Java" ); arrayList.add( "Data Structures" ); arrayList.add( "Algorithms" ); LinkedList When to Use: LinkedList is suitable for frequent insertions and deletions. It provides better performance than ArrayList in scenarios where elements are frequently added or removed from the middle of the list. Example Code: java LinkedList<String> linkedList = new LinkedList <>(); linkedList.add( "Java" ); linkedList.add( "Data Structures" ); linkedList.add( "Algorithms" ); HashMap When to Use: Use HashMap for fast retrieval of data based on a key. It is efficient for loo...
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...