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...

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 to Character.
  • The result is a list of individual characters.

2. Count Occurrences of Each Character


Map<Character, Long> freq = str.chars()
    .mapToObj(c -> (char) c)
    .collect(Collectors.groupingBy(c -> c, Collectors.counting()));

🧾 Explanation:

  • We group characters using groupingBy and count how many times each appears.
  • Output: {a=2, b=1, c=3} – super useful for frequency analysis.

3. Remove Duplicate Characters


String unique = str.chars()
    .distinct()
    .mapToObj(c -> String.valueOf((char) c))
    .collect(Collectors.joining());

🧾 Explanation:

  • distinct() removes repeated characters.
  • We join them back into a string using Collectors.joining().

4. Reverse a String Using Streams


String reversed = new StringBuilder(str)
    .reverse()
    .toString();

🧾 Explanation:

  • Not a stream, but the most efficient and readable way in Java.
  • Streams aren’t ideal for string reversal.

5. Check if a String is a Palindrome Using Streams


boolean isPalindrome = IntStream.range(0, str.length() / 2)
    .allMatch(i -> str.charAt(i) == str.charAt(str.length() - i - 1));

🧾 Explanation:

  • Compares characters from both ends using IntStream.range() and allMatch.
  • Efficient and elegant.

6. Count Vowels in a String


long vowelCount = str.toLowerCase().chars()
    .filter(c -> "aeiou".indexOf(c) >= 0)
    .count();

🧾 Explanation:

  • Converts string to lowercase.
  • Filters vowels using indexOf().
  • Counts how many vowels are present.

7. Splitting a String and Processing Words


List<String> words = Arrays.stream(str.trim().split("\\s+"))
    .collect(Collectors.toList());

🧾 Explanation:

  • .trim() removes leading/trailing spaces.
  • .split("\\s+") splits the string on any number of spaces, tabs, or newlines.
  • We collect the split words into a list.
  • Useful for processing text, tokenization, or word-based analytics.

🧠 Section 2: Popular Interview Questions on Java Strings Using Streams (with Detailed Explanations)

These are some common string-based interview questions where Java Streams can be a clean and powerful solution. Let's walk through each with proper explanations.

✅ Q1. How do you count duplicate characters in a string using streams?

Map<Character, Long> duplicates = str.chars()
    .mapToObj(c -> (char) c)
    .collect(Collectors.groupingBy(c -> c, Collectors.counting()));

duplicates.entrySet().stream()
    .filter(entry -> entry.getValue() > 1)
    .forEach(System.out::println);

πŸ“œ Explanation:
str.chars() gives a stream of character codes (int).
.mapToObj(c -> (char) c) converts each int to a Character object.
Collectors.groupingBy(..., Collectors.counting()) creates a frequency map.
.entrySet().stream().filter(... > 1) filters duplicates.
System.out::println prints them in character=count format.

✅ Q2. How do you find the first non-repeating character in a string?

Optional<Character> firstUnique = str.chars()
    .mapToObj(c -> (char) c)
    .collect(Collectors.groupingBy(c -> c, LinkedHashMap::new, Collectors.counting()))
    .entrySet().stream()
    .filter(entry -> entry.getValue() == 1)
    .map(Map.Entry::getKey)
    .findFirst();

πŸ“œ Explanation:
We use LinkedHashMap to preserve insertion order.
Filter entries with count == 1, then use findFirst().

✅ Q3. How do you check if two strings are anagrams using streams?

boolean isAnagram = Arrays.equals(
    str1.chars().sorted().toArray(),
    str2.chars().sorted().toArray()
);

πŸ“œ Explanation:
Convert strings to sorted character arrays and compare using Arrays.equals(...).

✅ Q4. How do you get all unique characters from a string using streams?

Set<Character> uniqueChars = str.chars()
    .mapToObj(c -> (char) c)
    .collect(Collectors.toSet());

πŸ“œ Explanation:
Collectors.toSet() stores only distinct characters.

✅ Q5. Write a program to remove whitespaces and convert the result to a stream of characters.

String cleaned = str.replaceAll("\\s+", "");

List<Character> charStream = cleaned.chars()
    .mapToObj(c -> (char) c)
    .collect(Collectors.toList());

πŸ“œ Explanation:
Remove all whitespaces using replaceAll, then convert to character list.

✅ Q6. How to count words in a sentence using streams?

String sentence = "Java is fun and powerful";

long wordCount = Arrays.stream(sentence.trim().split("\\s+")).count();

πŸ“œ Explanation:
Split on one or more whitespace characters, then count the elements.

✅ Q7. How do you find the most frequent character using streams?

Character mostFrequent = str.chars()
    .mapToObj(c -> (char) c)
    .collect(Collectors.groupingBy(c -> c, Collectors.counting()))
    .entrySet().stream()
    .max(Map.Entry.comparingByValue())
    .map(Map.Entry::getKey)
    .orElse(null);

πŸ“œ Explanation:
Group by character and count, then use max(...) with comparingByValue() to get the most frequent one.

🏁 Conclusion

Streams make string processing in Java more powerful, readable, and concise. From splitting words to finding the most frequent characters, Java 8 streams empower you to write expressive and efficient code. Mastering these concepts not only boosts your productivity but also prepares you for real-world coding interviews.

If you’re just getting started, try rewriting your old loop-based string problems using streams—you’ll start seeing how elegant your Java code can become. 

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...

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...