Skip to main content

Retry module - Resilience4j

as we discussed about circuit breaker module from resilience4j earlier, let's see what Retry module actually offers What is Retry in Resilience4j? this module offers ways of handling failure transaction by automatically retrying those transactions as per properties we configure. let's check how it works in this article. below code shows, how we can add retry annotation to our feign client Note: There is no need to add a fallbackMethod in the @Retry annotation if it is already defined in @CircuitBreaker . @GetMapping("/users/{userId}/albums") @Retry(name="album-service") @CircuitBreaker(name = "album-service", fallbackMethod = "getAlbumsFallbackMethod") public List<AlbumResponseModel> getAlbums(@PathVariable String userId); default List<AlbumResponseModel> getAlbumsFallbackMethod(String userId, Throwable exception) { System.out.println("user id" + userId); System.out.println("exc...

Java Streams Interview Questions and Solutions

 Java Streams are a powerful feature introduced in Java 8 that enable functional-style operations on collections. Recently, I was asked a few Java Streams-related questions in an interview, and I would like to share my solutions along with explanations and better alternatives where applicable.

Interview Questions and Solutions

1. Get Employees Whose Salary is Greater Than 6000 and Name Starts With 'S'

Question:

Given a list of employees, filter out employees who earn more than 6000 and whose names start with the letter 'S'.

Solution:

List<Employee> empStartsWithS = employees.stream()
    .filter(e -> e.getSalary() > 6000.0 && e.getName().toLowerCase().startsWith("s"))
    .collect(Collectors.toList());

System.out.println(empStartsWithS);

Explanation:

  • filter() is used to apply the condition: salary > 6000 and name starts with 's'.
  • collect(Collectors.toList()) collects the filtered elements into a new list.

Better Solution?

The current solution is optimal, but if case-sensitivity is not a concern, you can directly use startsWith("S") instead of toLowerCase().


2. Give a 40% Salary Hike to Each Employee and Print

Question:

Increase the salary of all employees by 40% and print the updated list.

Solution:

List<Employee> hiked = employees.stream()
    .map(e -> new Employee(e.getId(), e.getName(), e.getSalary() * 1.4))
    .collect(Collectors.toList());

System.out.println(hiked);

Explanation:

  • map() is used to transform each employee object.
  • A new Employee object is created with an updated salary.
  • collect(Collectors.toList()) gathers the transformed employees into a list.

Why Create a New Employee Object?

If we modify the existing object inside map(), the original list (employees) will also be affected because Java passes object references. Creating a new object ensures immutability and prevents unintended modifications.

Wrong approach (Modifies existing list):

employees.stream()
    .peek(e -> e.setSalary(e.getSalary() * 1.4))
    .collect(Collectors.toList());

This approach changes employees directly, which might not be desirable.


3. Find the Employee with the Maximum Salary

Question:

Find the employee with the highest salary in the given list.

Solution:

Double maxSalariedEmp = employees.stream()
    .max(Comparator.comparingDouble(Employee::getSalary))
    .get()
    .getSalary();

System.out.println(maxSalariedEmp);

Explanation:

  • max(Comparator.comparingDouble(Employee::getSalary)) finds the employee with the highest salary.
  • .get() retrieves the Optional<Employee> result (ensure the list is non-empty).
  • .getSalary() fetches the actual salary value.

Better Solution?

If you need the full employee details instead of just the salary, modify it like this:

Optional<Employee> maxEmployee = employees.stream()
    .max(Comparator.comparingDouble(Employee::getSalary));

maxEmployee.ifPresent(System.out::println);

This prevents a NoSuchElementException if the list is empty.


Conclusion

These were some common interview questions based on Java Streams. Mastering these concepts can help in real-world applications where we need efficient data processing.

Key Takeaways:

  • Use filter() for selecting specific elements from a stream.
  • Use map() to transform objects and maintain immutability.
  • Use max() with a comparator to find the highest value.
  • Prefer creating new objects in transformations to avoid modifying the original list.

Comments

Popular posts from this blog

Retry module - Resilience4j

as we discussed about circuit breaker module from resilience4j earlier, let's see what Retry module actually offers What is Retry in Resilience4j? this module offers ways of handling failure transaction by automatically retrying those transactions as per properties we configure. let's check how it works in this article. below code shows, how we can add retry annotation to our feign client Note: There is no need to add a fallbackMethod in the @Retry annotation if it is already defined in @CircuitBreaker . @GetMapping("/users/{userId}/albums") @Retry(name="album-service") @CircuitBreaker(name = "album-service", fallbackMethod = "getAlbumsFallbackMethod") public List<AlbumResponseModel> getAlbums(@PathVariable String userId); default List<AlbumResponseModel> getAlbumsFallbackMethod(String userId, Throwable exception) { System.out.println("user id" + userId); System.out.println("exc...

Mastering Java Streams: Smart Ways to Handle Strings Like a Pro

Working with strings is a daily task for Java developers. But if you're still stuck in loops and if-else blocks, it’s time to level up! 💪 Java Streams offer a clean, expressive, and functional way to process strings—whether you're transforming, filtering, or analyzing them. In this blog, we’ll explore: 🛠️ Different ways to use streams on strings in Java 💼 Popular interview questions involving Java strings and streams Whether you're a beginner or an experienced developer preparing for interviews, this guide has you covered. ✨ Section 1: Different Approaches to Use Streams on Strings in Java Let’s look at how to apply Java Streams on strings using various real-world examples. 1. Convert a String to a List of Characters List<Character> characters = str.chars() .mapToObj(c -> (char) c) .collect(Collectors.toList()); 🧾 Explanation: str.chars() returns an IntStream of character codes. .mapToObj(c -> (char) c) casts each int...

circuit breaker and its events - resilience4j

In this article, let's discuss about circuit breaker, its properties, and some of its events. What is a Circuit Breaker? It is a fault tolerance mechanism used in microservices. It is a part of Resilience4j . Circuit breaker is used to avoid multiple calls to non-responding microservices, preventing cascading failures. How to Use Circuit Breaker To use circuit breaker, add the below dependencies in your pom.xml : <dependency> <groupId>io.github.resilience4j<groupId> <artifactId>resilience4j-spring-boot2<artifactId> <dependency> <dependency> <groupId>org.springframework.boot<groupId> <artifactId>spring-boot-starter-aop<artifactId> <dependency> Assuming we are using Feign Client for communication between microservices, here's an example from a user microservice calling an album microservice: @FeignClient(name = "album-service") public interface Albu...