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 anIntStreamof character codes..mapToObj(c -> (char) c)casts each int toCharacter.- 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
groupingByand 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()andallMatch. - 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
Post a Comment