Advanced Senior Java Lead Interview Queries Explained
Written on
Question: Differentiate between findAny and findFirst, and under what circumstances might you opt for one over the other?
The method findFirst retrieves the initial element of the stream, following the order of elements if such an order is defined. Conversely, findAny can yield any element from the stream and is generally more efficient in parallel processing since it doesn’t impose an order of operation.
Question: When should you consider using Parallel Streams and what are the reasons?
Parallel streams should be employed when:
- There is a substantial dataset to process in a similar manner.
- The order of data does not influence the outcome.
- The items are independent of each other.
- A particular processing phase is a performance bottleneck.
For instance, to calculate the sum of a large list of integers, we can implement the following code:
package collectors;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class ParallelStreamsDemo {
public static void main(String[] args) {
// Generate a large list of random integers
List<Integer> numbers = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < 1_000_000; i++) {
numbers.add(random.nextInt(100));}
// Compute the sum using parallel stream
long startTime = System.currentTimeMillis();
int sum = numbers.stream().reduce(0, Integer::sum);
long endTime = System.currentTimeMillis();
System.out.println("Sum: " + sum);
System.out.println("Time taken with parallel stream: " + (endTime - startTime) + " ms");
}
}
Question: If you have a collection of Orders, where each Order consists of Edibles like Fruits with their respective quantities and prices, how would you determine the total expenditure on each Fruit across all orders?
This task necessitates grouping and summarizing skills.
Orders Model
package collectors.model;
import java.util.List;
class Orders {
List<Item> items;}
Item Model
package collectors.model;
public class Item {
String name;
double price;
int quantity;
}
Results: Below is the total cost for each Fruit across all orders.
package collectors;
import collectors.model.Item;
import collectors.model.Orders;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ItemPriceAggregator {
public static void main(String[] args) {
List<Orders> orders = Arrays.asList(
new Orders(Arrays.asList(
new Item("Pears", 200.45, 22),
new Item("Mangoes", 120.45, 45),
new Item("Oranges", 145.67, 22),
new Item("Mandarins", 207.45, 89))),
new Orders(Arrays.asList(
new Item("Pears", 200.45, 21),
new Item("Mangoes", 120.45, 459),
new Item("Oranges", 345.67, 22),
new Item("Mandarins", 207.45, 89)))
);
Map<String, Double> totalAmountPerItem = orders.stream()
.flatMap(order -> order.items.stream())
.collect(Collectors.groupingBy(Item::getName,
Collectors.summingDouble(item -> item.price * item.quantity)));totalAmountPerItem.entrySet().stream()
.forEach(entry -> System.out.println(entry.getKey() + " = " + entry.getValue()));}
}
Question: How can you create a Stream from a File?
Stream<String> lines = Files.lines(Paths.get("file.txt"));
Question: What is the purpose of the peek method in a Stream?
The peek method serves as an intermediate operation primarily used for debugging, allowing you to execute an action on each element of the stream as they are processed. For example:
Question: How can you convert a Stream to an array?
String[] array = stream.toArray(String[]::new);
Question: How do you calculate the average salary for employees earning more than 50000 in each department?
Employee Model
package collectors.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.math.BigDecimal;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
private String name;
private Department department;
private BigDecimal salary;
}
Department Model
package collectors.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private String name;}
Finding average salary in each department for salaries greater than 50000.
package collectors.model;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class AverageSalaryByDept {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("Vikas", new Department("IT"), new BigDecimal("212345.67")),
new Employee("Ravi", new Department("Commercial"), new BigDecimal("12345.67")),
new Employee("Rajni", new Department("Procurement"), new BigDecimal("322345.67")),
new Employee("Sinha", new Department("Commercial"), new BigDecimal("42345.67"))
);
Map<Department, Double> averageSalaryByDepartment = employees.stream()
.filter(e -> e.getSalary().compareTo(new BigDecimal("50000")) > 0)
.collect(Collectors.groupingBy(Employee::getDepartment,
Collectors.mapping(Employee::getSalary,
Collectors.averagingDouble(BigDecimal::doubleValue))));averageSalaryByDepartment.entrySet().stream()
.forEach(entry -> System.out.println(entry.getKey().getName() + " = " + entry.getValue()));}
}
Results:
I trust you found these practical examples of Java Streams and their applications helpful. If you enjoyed the article, please share and show your appreciation. Thank you for your support!