MOST ASKED STREAMS PROBLEMS

If you are a Java developer or full stack developer, it is very much important to know the streams concept and its usages. I have listed down important stream problems you should know before attending any Java interview.
Find first repeated character in a string
There are two methods that are mostly used.
a. using indexing:
Here we check if the character’s firstIndex and lastIndex are same. If yes, then it’s not repeated, else it is repeated.
example:
Str = “india”;
repeated characters — i
non-repeated characters — n, d, a
explanation: Now here first index of “i” is 0 and lastIndex of “i” is 3. Both are not same, so it is repeated. And firstIndex of “n” and lastIndex of “n” are 1, so it is not repeated. Same with “d”, “a” too.
code:
import java.util.*;
import java.util.stream.*;
class Main {
public static void main(String[] args) {
String str = "india";
String s = Arrays.stream(str.split(""))
.filter(x->str.indexOf(x) == str.lastIndexOf(x))
.findFirst()
.get();
System.out.print(s);
}
}
b. using HashMap
Here first you store in map and iterate through the values and filter whose value is 1 and map their keys and fetch them.
Here we use LinkedHashMap to maintain order.
import java.util.*;
import java.util.stream.*;
class Main {
public static void main(String[] args) {
String str = "india";
String s = Arrays.stream(str.split(""))
.collect(Collectors.groupingBy(x->x,
LinkedHashMap::new,
Collectors.counting()))
.entrySet()
.stream()
.filter(x->x.getValue() == 1)
.map(x->x.getKey())
.findFirst()
.get();
System.out.print(s);
}
}
explanation: Arrays.stream(str.split(“”)) will split single characters as strings. Collectors.groupingBy(x->x, LinkedHashMap::new, Collectors.counting()) will help in storing those in form of HashMap and LinkedHashMap will help in storing in same order of input. Then we convert into stream again since it is now in form of HashMap. Now over that stream we perform filter operation by checking whose value is 1. If 1, we consider that means it is unique. So now we map their keys and fetch it. Here findFirst we are using because we have possibility of multiple keys whose value is 1. In our case we have n, d, a. To fetch only first one we are using findFirst.
Print only repeated characters in a string
Here.. again we can do with both above methods but here I am using HashMap because HashMap is very frequently used for multiple operations.
import java.util.*;
import java.util.stream.*;
class Main {
public static void main(String[] args) {
String str = "india";
List<String> s = Arrays.stream(str.split(""))
.collect(Collectors.groupingBy(x->x,
LinkedHashMap::new,
Collectors.counting()))
.entrySet()
.stream()
.filter(x->x.getValue() > 1)
.map(x->x.getKey())
.toList();
System.out.print(s);
}
}
explanation:
Here we are storing in HashMap and converting it into stream and filtering whose value is greater than 1 and collecting into list using toList().
Find strings in a list that start with a number
You are given an array of strings [“pink”,”1blue”,”2red”]
input — [“pink”,”1blue”,”2red”]
output — [“1blue”,”2red”]
import java.util.*;
import java.util.stream.*;
class Main {
public static void main(String[] args) {
List<String> l = Arrays.asList("pink","1blue","2red");
List<String> s = l.stream()
.filter(x-> Character.isDigit(x.charAt(0)))
.toList();
System.out.print(s);
}
}
explanation: We are iterating over list of strings and filtering the strings whose first character is digit using Character.isDigit().
Find strings in a list that start with a vowel
Here we don’t have any inbuilt method like .isDigit, so we make a list of vowels and check if the first character of our string is present in vowels list.
import java.util.*;
import java.util.stream.*;
class Main {
public static void main(String[] args) {
List<Character> l = Arrays.asList('A','E','I','O','U','a','e','i','o','u');
List<String> n = Arrays.asList("ink","1blue","2red");
List<String> s = n.stream()
.filter(x-> l.contains(x.charAt(0)))
.collect(Collectors.toList());
System.out.print(s);
}
}
explanation:
We create list of vowels.
Iterate over given list and filter the strings whose first character is present in vowels list using filter(x-> l.contains(x.charAt(0))).
Store it in list.
Find strings in a list that start with a consonant
This is similar to above problem but vice versa. I am not giving any explanation for this. Hope you will understand the solution.
import java.util.*;
import java.util.stream.*;
class Main {
public static void main(String[] args) {
List<Character> l = Arrays.asList('A','E','I','O','U','a','e','i','o','u');
List<String> n = Arrays.asList("ink","1blue","2red");
List<String> s = n.stream()
.filter(x-> !l.contains(x.charAt(0)))
.collect(Collectors.toList());
System.out.print(s);
}
}
Find sum of digits in a number
This is the problem that I personally have been asked at Deloitte.
Here you are given an integer n = 1234. You should print sum of each digit, which means 10.
Algorithm:
First convert number into string (why? it will be easy to apply operations like split(“”) or chars() to fetch individual characters. If it is direct number it is complicated).
Apply chars() to get access to individual characters.
This is important: always remember to convert a char to number you have to do — ‘0’. Since right now we are in char format, we should do same.
Apply sum() over digits.
import java.util.*;
import java.util.stream.*;
class Main {
public static void main(String[] args) {
int n = 2345;
int sum = String.valueOf(n).chars().map(x->x-'0').sum();
System.out.print(sum);
}
}
convert to string → to chars → map char to digit → sum
Below is the similar question, so try on your own. However, I am adding the solution.
Find sum of digits in a string (only numbers exist)
import java.util.*;
import java.util.stream.*;
class Main {
public static void main(String[] args) {
String n = "2345";
int sum = n.chars().map(x->x-'0').sum();
System.out.print(sum);
}
}
Find the reverse of a number
This is also similar concept but with a small twist.
Here you are given a number n = 12345. You convert it into 54321.
Algorithm:
- Convert number into string.
- Convert to stream and collect in list.
- Reverse.
- Convert to stream and collect as string.
import java.util.*;
import java.util.stream.*;
class Main {
public static void main(String[] args) {
int m = 2345;
String n = String.valueOf(m);
String ans = Arrays.stream(n.split(""))
.collect(Collectors.toList())
.reversed()
.stream()
.collect(Collectors.joining());
System.out.print(ans);
}
}
in the same try if given input is string.
Find if given string palindrome or not
Algorithm:
- Use IntStream to create a reversed string from 0 to n indexes where n is size of given string.
- Use mapToObj since we are mapping int to string.
- We are converting to string for each char because we will compare string to string, not string to char in the end.
- Now collect each string as entire string (you get in reversed form).
- Compare using equals with original string. If true then palindrome else not.
import java.util.*;
import java.util.stream.*;
class Main {
public static void main(String[] args) {
String str = "madam";
int n = str.length();
boolean ans = IntStream.range(0,n)
.mapToObj(x->String.valueOf(str.charAt(n-x-1)))
.collect(Collectors.joining())
.equals(str);
System.out.print(ans);
}
}
Find most repeated element in an array
This is classic question that is usually asked in interviews. Here we’ll solve using HashMap. By now you will be able to solve this. If not, there is algo and code below.
Algorithm:
- Iterate over the list and store in form of map where keys are integers and values are number of occurrences.
- Iterate over map stream and find max over the values.
- Map with key.
- Fetch.
import java.util.*;
import java.util.stream.*;
class Main {
public static void main(String[] args) {
List<Integer> l = Arrays.asList(12,1,2,11,12,1,2,1,2,2);
int ans = l.stream()
.collect(Collectors.groupingBy(x->x,Collectors.counting()))
.entrySet()
.stream()
.max(Map.Entry.comparingByValue())
.map(x->x.getKey())
.get();
System.out.print(ans);
}
}
Find all most repeated elements
Consider we have array of integers [2,6,2,3,3,3,3,7,7,7,7]. All occurrences of most repeated elements. In this case it will be [3,7].
Algorithm:
- Create a map with the given list where key is integer and value is number of occurrences.
- Find the max frequency.
- Find all the values with the above calculated max frequency.
import java.util.stream.*;
class Main {
public static void main(String[] args) {
int[] list = {2,6,2,3,3,3,3,7,7,7,7};
Map<Integer, Long> map = Arrays.stream(list)
.boxed()
.collect(Collectors.groupingBy(x->x, Collectors.counting()));
int freq = map.entrySet()
.stream()
.max(Map.Entry.comparingByValue())
.map(x->x.getValue())
.map(Long::intValue)
.get();
List<Integer> ans = map
.entrySet()
.stream()
.filter(x->x.getValue() == freq)
.map(x->x.getKey())
.toList();
System.out.print(ans);
}
}
Final Thoughts:
Sometimes you might feel overwhelmed seeing stream problems because I felt that too and I still feel it even now. Just keep practicing as many problems as you can and learn the usages. You’ll already be ahead in 70% of interviews. Feel free to ping me if you have any queries.
contact: [email protected]
MOST ASKED STREAMS PROBLEMS was originally published in Javarevisited on Medium, where people are continuing the conversation by highlighting and responding to this story.
This post first appeared on Read More

