Stream API - jiquest

add

#

Stream API

50+ Interview Question & Answer on Java Stream API 


1.  Given a list of `Student` objects, filter out the students who have a GPA less than 3.0 and collect their names into a list.

List studentNames = students.stream() .filter(s -> s.getGpa() >= 3.0) .map(Student::getName) .collect(Collectors.toList());

 

2.  From a list of integers, find the first even number greater than 10. If none exist, return `Optional.empty()`.

Optional firstEven = numbers.stream() .filter(n -> n > 10 && n % 2 == 0) .findFirst();

 

3.  You have a list of `Employee` objects. Sort them by their salary in descending order and collect the result into a list.

List < Employee > sortedEmployees = employees.stream() .sorted(Comparator.comparing(Employee::getSalary).reversed()) .collect(Collectors.toList());

 

4. Given a list of `Order` objects, extract the order amounts and calculate the total sum.

double totalAmount = orders.stream() .mapToDouble(Order::getAmount) .sum();

 

5. Given a list of `Transaction` objects, count how many transactions are of type "CREDIT".

long creditCount = transactions.stream() .filter(t -> "CREDIT".equals(t.getType())) .count();

 

6. From a list of strings, find all unique strings (case-insensitive) and collect them into a set.

Set < String > uniqueStrings = strings.stream() .map(String::toLowerCase) .collect(Collectors.toSet());

 

7. From a list of numbers, skip the first 5 elements and then collect the next 10 elements into a new list.

List < Integer > sublist = numbers.stream() .skip(5) .limit(10) .collect(Collectors.toList());

 

8. Given a list of `Customer` objects where each customer has a list of `Order` objects, find all unique products ordered by all customers.

Set < Product > uniqueProducts = customers.stream() .flatMap(customer -> customer.getOrders().stream()) .flatMap(order -> order.getProducts().stream()) .collect(Collectors.toSet());

 

9. Given a list of integers, find the product of all non-zero elements.

int product = numbers.stream() .filter(n -> n != 0) .reduce(1, (a, b) -> a * b);

 

10.  From a list of `Book` titles, create a single string where the titles are separated by commas.

String result = bookTitles.stream() .collect(Collectors.joining(", "));

 

11. Given a list of `Person` objects, partition the list into two groups: those older than 30 and those 30 or younger.

Map < Boolean, List < Person >> partitioned = people.stream() .collect(Collectors.partitioningBy(p -> p.getAge() > 30));

 

12. Given a list of `Transaction` objects, group the transactions by their status (e.g., PENDING, COMPLETED) and count how many transactions fall into each group.

Map < String, Long > transactionCounts = transactions.stream() .collect(Collectors.groupingBy(Transaction::getStatus, Collectors.counting()));

 

13. From a list of `Product` prices, calculate summary statistics (min, max, average, sum, and count).

DoubleSummaryStatistics stats = productPrices.stream() .collect(Collectors.summarizingDouble(Double::doubleValue));

 

14. From a list of `Employee` objects, find the employee with the longest tenure.

Optional < Employee > longestTenure = employees.stream() .max(Comparator.comparing(Employee::getTenure));

 

15. Convert a list of `Person` objects into a map where the key is the person's ID and the value is the person's name.

Map < Integer, String > personMap = people.stream() .collect(Collectors.toMap(Person::getId, Person::getName));

 

16. From a list of strings, find the length of the longest string.

int maxLength = strings.stream() .mapToInt(String::length) .max() .orElse(0);

 

17.  Given a list of `Employee` objects, filter out employees whose salaries are above a certain threshold and return the result as a set.

Set < Employee > filteredEmployees = employees.stream() .filter(e -> e.getSalary() > threshold) .collect(Collectors.toSet());

 

18. Given a list of `Person` objects, find the average age of people who are younger than 40.

double averageAge = people.stream() .filter(p -> p.getAge() < 40) .mapToInt(Person::getAge) .average() .orElse(0.0);

 

19. From a list of `Order` objects, find the order with the maximum amount.

Optional < Order > maxOrder = orders.stream() .max(Comparator.comparing(Order::getAmount));

 

20. Given a list of `Transaction` objects, find the total amount for transactions that are marked as "COMPLETED".

double totalCompletedAmount = transactions.stream() .filter(t -> "COMPLETED".equals(t.getStatus())) .mapToDouble(Transaction::getAmount) .sum();

 

21. Given a list of `Product` objects, group them by category and then by their availability status.

Map < String, Map < Boolean, List < Product >>> groupedProducts = products.stream() .collect(Collectors.groupingBy(Product::getCategory, Collectors.partitioningBy(Product::isAvailable)));

 

22. From a list of `Order` objects, extract a list of all customer names who have placed more than one order.

List < String > frequentCustomers = orders.stream() .collect(Collectors.groupingBy(Order::getCustomerName, Collectors.counting())) .entrySet().stream() .filter(entry -> entry.getValue() > 1) .map(Map.Entry::getKey) .collect(Collectors.toList());

 

23. Given a list of `Employee` objects, find the name of the highest-paid employee in each department.

Map < String, Optional < Employee >> highestPaidInDept = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.maxBy(Comparator.comparing(Employee::getSalary))));

 

24. Given a list of `Transaction` objects, create a map where the key is the transaction type and the value is a list of transaction IDs for that type.

Map < String, List < String >> transactionsByType = transactions.stream() .collect(Collectors.groupingBy(Transaction::getType, Collectors.mapping(Transaction::getId, Collectors.toList())));

 

25. Given a list of `Product` objects, group them by category and calculate the total stock available for each category.

Map < String, Integer > totalStockByCategory = products.stream() .collect(Collectors.groupingBy(Product::getCategory, Collectors.summingInt(Product::getStock)));

 

26. From a list of `Student` objects, find the top 3 students with the highest GPA.

List < Student > topStudents = students.stream() .sorted(Comparator.comparing(Student::getGpa).reversed()) .limit(3) .collect(Collectors.toList());

 

27. Given a list of `Employee` objects, collect the names of employees who joined in the last 2 years into a set.

Set < String > recentJoiners = employees.stream() .filter(e -> e.getJoinDate().isAfter(LocalDate.now().minusYears(2))) .map(Employee::getName) .collect(Collectors.toSet());

 

28. Given a list of `Order` objects, create a summary of the total amount spent by each customer.

Map < String, Double > totalSpentByCustomer = orders.stream() .collect(Collectors.groupingBy(Order::getCustomerName, Collectors.summingDouble(Order::getAmount)));

 

29. From a list of strings, create a map where the key is the length of the string and the value is a list of strings of that length.

Map < Integer, List < String >> stringsByLength = strings.stream() .collect(Collectors.groupingBy(String::length));

 

30. Given a list of `Transaction` objects, group the transactions by month and then by status.

Map>> transactionsByMonthAndStatus = transactions.stream() .collect(Collectors.groupingBy(t -> t.getDate().getMonth(), Collectors.groupingBy(Transaction::getStatus)));

 

31. Given a list of `Book` objects, find the most expensive book in each category and return the results as a map.

Map < String, Optional < Book >> mostExpensiveBooksByCategory = books.stream() .collect(Collectors.groupingBy(Book::getCategory, Collectors.maxBy(Comparator.comparing(Book::getPrice))));

 

32. From a list of `Employee` objects, create a map where the key is the department and the value is the average salary of employees in that department.

Map < String, Double > avgSalaryByDept = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.averagingDouble(Employee::getSalary)));

 

33. Given a list of `Customer` objects where each customer has a list of `Order` objects, find the customer who has placed the most orders.

Optional < Customer > mostActiveCustomer = customers.stream() .max(Comparator.comparingInt(c -> c.getOrders().size()));

 

34. Given a list of `Transaction` objects, group them by type and find the highest transaction amount for each type.

Map < String, Optional < Transaction >> maxTransactionByType = transactions.stream() .collect(Collectors.groupingBy(Transaction::getType, Collectors.maxBy(Comparator.comparing(Transaction::getAmount))));

 

35. From a list of `Employee` objects, find the total salary paid to employees in each department who have more than 5 years of experience.

Map < String, Integer > totalSalaryByDept = employees.stream() .filter(e -> e.getYearsOfExperience() > 5) .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.summingInt(Employee::getSalary)));

 

36. Given a list of `Order` objects, group them by customer and find the order with the maximum amount for each customer.

Map < String, Optional < Order >> maxOrderByCustomer = orders.stream() .collect(Collectors.groupingBy(Order::getCustomerName, Collectors.maxBy(Comparator.comparing(Order::getAmount))));

 

37. From a list of `Person` objects, find the most common city of residence.

String mostCommonCity = people.stream() .collect(Collectors.groupingBy(Person::getCity, Collectors.counting())) .entrySet().stream() .max(Map.Entry.comparingByValue()) .map(Map.Entry::getKey) .orElse("No city");

 

38. Given a list of `Student` objects, create a map where the key is the grade (A, B, C, etc.) and the value is a list of students who received that grade.

Map < String, List < Student >> studentsByGrade = students.stream() .collect(Collectors.groupingBy(Student::getGrade));

 

39. Given a list of `Employee` objects, find the department with the highest average salary.

String departmentWithHighestAvgSalary = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.averagingDouble(Employee::getSalary))) .entrySet().stream() .max(Map.Entry.comparingByValue()) .map(Map.Entry::getKey) .orElse("No department");

 

40. From a list of `Transaction` objects, create a report that shows the total transaction amount by type and by month.

Map < String, Map < Month, Double >> totalAmountByTypeAndMonth = transactions.stream() .collect(Collectors.groupingBy(Transaction::getType, Collectors.groupingBy(t -> t.getDate().getMonth(), Collectors.summingDouble(Transaction::getAmount))));

 

41.  Given a list of `Order` objects, find the average order amount for each customer.

Map < String, Double > avgOrderAmountByCustomer = orders.stream() .collect(Collectors.groupingBy(Order::getCustomerName, Collectors.averagingDouble(Order::getAmount)));

 

42. Given a list of `Product` objects, find the total number of products available in each category and return the result as a map.

Map < String, Long > productCountByCategory = products.stream() .collect(Collectors.groupingBy(Product::getCategory, Collectors.counting()));

 

43. Given a list of `Transaction` objects, find the top 5 transactions by amount for each type.

Map < String, List < Transaction >> top5TransactionsByType = transactions.stream() .collect(Collectors.groupingBy(Transaction::getType, Collectors.collectingAndThen( Collectors.toList(), list -> list.stream() .sorted(Comparator.comparing(Transaction::getAmount).reversed()) .limit(5) .collect(Collectors.toList()))));

 

44.  From a list of `Employee` objects, find the department with the most employees.

String deptWithMostEmployees = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting())) .entrySet().stream() .max(Map.Entry.comparingByValue()) .map(Map.Entry::getKey) .orElse("No department");

 

45. Given a list of `Order` objects, find all orders where the total amount exceeds a certain threshold and return them as a list.

List < Order > highValueOrders = orders.stream() .filter(order -> order.getAmount() > threshold) .collect(Collectors.toList());

 

46. Given a list of `Product` objects, create a map where the key is the product category and the value is a list of products sorted by price in descending order.

Map < String, List < Product >> productsByCategorySortedByPrice = products.stream() .collect(Collectors.groupingBy(Product::getCategory, Collectors.collectingAndThen(Collectors.toList(), list -> list.stream() .sorted(Comparator.comparing(Product::getPrice).reversed()) .collect(Collectors.toList()))));

 

47. From a list of `Person` objects, create a map where the key is the city and the value is the average age of people in that city.

Map < String, Double > avgAgeByCity = people.stream() .collect(Collectors.groupingBy(Person::getCity, Collectors.averagingInt(Person::getAge)));

 

48. Given a list of `Transaction` objects, find the total amount for each transaction type, but only include types where the total amount is above a certain threshold.

Map < String, Double > totalAmountByTypeAboveThreshold = transactions.stream() .collect(Collectors.groupingBy(Transaction::getType, Collectors.summingDouble(Transaction::getAmount))) .entrySet().stream() .filter(entry -> entry.getValue() > threshold) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

 

49. From a list of `Book` objects, find the average price of books in each category.

Map < String, Double > avgPriceByCategory = books.stream() .collect(Collectors.groupingBy(Book::getCategory, Collectors.averagingDouble(Book::getPrice)));

 

50.  Given a list of `Employee` objects, find the name of the employee with the second highest salary.

Optional < String > secondHighestSalaryEmployee = employees.stream() .sorted(Comparator.comparing(Employee::getSalary).reversed()) .skip(1) .map(Employee::getName) .findFirst();

 

51. You have a list of Employee objects, and you need to create a list of all employees who are older than 30 and whose name starts with the letter "A". The resulting list should only include their names in uppercase.

List < String > employeeNames = employees.stream() .filter(e -> e.getAge() > 30) .filter(e -> e.getName().startsWith("A")) .map(e -> e.getName().toUpperCase()) .collect(Collectors.toList());

 

52: Given a list of Transaction objects, where each transaction has a type (String) and an amount (double), group the transactions by their type and calculate the total amount for each type.

Map < String, Double > totalAmountByType = transactions.stream() .collect(Collectors.groupingBy( Transaction::getType, Collectors.summingDouble(Transaction::getAmount) ));

 

53: You have a list of Product objects, and you need to find the product with the highest price. If the list is empty, return Optional.empty().

Optional < Product > mostExpensiveProduct = products.stream() .max(Comparator.comparing(Product::getPrice));

 

54: You have a large list of integers and need to find the sum of all the even numbers. Since the list is large, you want to do this operation in parallel to improve performance.

int sumOfEvens = integers.parallelStream() .filter(n -> n % 2 == 0) .mapToInt(Integer::intValue) .sum();

 

55: Given a list of Customer objects, where each customer has a list of Order objects, find all unique products ordered by customers. Each Order contains a list of Product objects.

Set < Product > uniqueProducts = customers.stream() .flatMap(customer -> customer.getOrders().stream()) .flatMap(order -> order.getProducts().stream()) .collect(Collectors.toSet());

 

56: You have a list of Student objects, where each student has a name and a list of Grade objects. You need to create a map where the key is the student's name and the value is the average grade.

Map < String, Double > averageGrades = students.stream() .collect(Collectors.toMap( Student::getName, student -> student.getGrades().stream() .mapToInt(Grade::getScore) .average() .orElse(0.0) ));

 

57: You have a list of sentences (strings) and need to find the longest word in all the sentences. The sentences are separated by spaces, and the words should be compared based on their length.

Optional < String > longestWord = sentences.stream() .flatMap(sentence -> Arrays.stream(sentence.split(" "))) .max(Comparator.comparingInt(String::length));

 

58: You have a list of Person objects and need to collect all unique names in a TreeSet, sorted by the length of the names.

Set < String > uniqueSortedNames = people.stream() .map(Person::getName) .collect(Collectors.toCollection(() -> new TreeSet < > (Comparator.comparingInt(String::length)) ));

 

59: You have a list of Integer values and want to calculate the product of all non-zero numbers. If the list contains only zeros, return Optional.empty().

Optional < Integer > product = integers.stream() .filter(n -> n != 0) .reduce((a, b) -> a * b);

 

60: You are processing a large file line by line. You need to read the file, filter out lines that are empty or start with a # (indicating a comment), and collect the first 100 non-empty, non-comment lines into a list.

try (Stream < String > lines = Files.lines(Paths.get("largefile.txt"))) { List < String > first100Lines = lines.filter(line -> !line.isEmpty() && !line.startsWith("#")) .limit(100) .collect(Collectors.toList()); } catch (IOException e) { e.printStackTrace(); }

 

61: You have three different lists of Order objects, each representing orders from different regions. You need to create a single list containing all orders from these three lists, without duplicates.

List < Order > allOrders = Stream.of(ordersRegion1, ordersRegion2, ordersRegion3) .flatMap(Collection::stream) .distinct() .collect(Collectors.toList());

 

62: You have a list of Person objects, and each person has a city of residence. Count how many people live in each city, but only include cities with more than 10 residents.

Map < String, Long > cityCounts = people.stream() .collect(Collectors.groupingBy(Person::getCity, Collectors.counting())) .entrySet().stream() .filter(entry -> entry.getValue() > 10) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

 

63: You have a list of Book objects, each with a title, author, and price. Sort the books first by author’s name, then by price in descending order.

List < Book > sortedBooks = books.stream() .sorted(Comparator.comparing(Book::getAuthor) .thenComparing(Comparator.comparing(Book::getPrice).reversed())) .collect(Collectors.toList());

 

64: You have a list of Transaction objects, and you need to generate a report of the total amount of transactions for each month. Each transaction has a date and amount.

Map < Month, Double > totalByMonth = transactions.stream() .collect(Collectors.groupingBy( t -> t.getDate().getMonth(), Collectors.summingDouble(Transaction::getAmount) ));

 

65: You have a list of Department objects, where each department has a list of Employee objects. You need to find the employee with the highest salary across all departments.

Optional < Employee > highestPaidEmployee = departments.stream() .flatMap(department -> department.getEmployees().stream()) .max(Comparator.comparing(Employee::getSalary));

 

-------------------------------------------------Happy Learning!-------------------------------------------------------