Coding Practice — Stream API¶
EPAM-style Java 8 Stream API coding problems frequently asked in interviews.
1. Longest string with all unique characters¶
Given a list of strings, find the string which has the longest length and in which all characters are unique. If ties, return the first. If no string meets the criteria, return an empty string.
public static String longestUniqueString(List<String> strings) {
return strings.stream()
.filter(s -> s.chars().distinct().count() == s.length()) // all unique chars
.max(Comparator.comparingInt(String::length))
.orElse("");
}
// Test
List<String> words = Arrays.asList("hello", "world", "abcde", "abc", "xyz");
System.out.println(longestUniqueString(words)); // "abcde"
2. Group strings by first letter¶
Write a method that takes a list of strings and groups them by their first letter. Result: Map<Character, List<String>>.
public static Map<Character, List<String>> groupByFirstLetter(List<String> strings) {
return strings.stream()
.filter(s -> s != null && !s.isEmpty())
.collect(Collectors.groupingBy(s -> s.charAt(0)));
}
// Test
List<String> words = Arrays.asList("apple", "banana", "avocado", "blueberry", "cherry");
System.out.println(groupByFirstLetter(words));
// {a=[apple, avocado], b=[banana, blueberry], c=[cherry]}
3. Most frequently occurring character¶
Find the most frequently occurring character in a string (case-sensitive).
public static char mostFrequentChar(String str) {
return str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElseThrow();
}
// Test
System.out.println(mostFrequentChar("programming")); // 'g' (appears 2 times)
4. Average of squares greater than N¶
Calculate the average of squares of numbers greater than N.
public static double avgOfSquaresGreaterThan(List<Integer> numbers, int n) {
return numbers.stream()
.filter(num -> num > n)
.mapToInt(num -> num * num)
.average()
.orElse(0.0);
}
// Test
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
System.out.println(avgOfSquaresGreaterThan(nums, 5)); // avg of 36,49,64,81,100 = 66.0
5. First non-repeating character¶
Find the first non-repeating character in a given string.
public static Character firstNonRepeating(String str) {
return str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(),
LinkedHashMap::new, Collectors.counting())) // LinkedHashMap preserves insertion order
.entrySet().stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);
}
// Test
System.out.println(firstNonRepeating("aabbcddeff")); // 'c'
System.out.println(firstNonRepeating("swiss")); // 'w'
6. Second highest word length¶
Find the second highest length in a given sentence of words.
public static int secondHighestLength(String sentence) {
return Arrays.stream(sentence.split("\\s+"))
.map(String::length)
.distinct() // remove duplicate lengths
.sorted(Comparator.reverseOrder()) // descending
.skip(1) // skip the highest
.findFirst()
.orElse(-1);
}
// Test
System.out.println(secondHighestLength("The quick brown fox jumps"));
// Lengths: The=3, quick=5, brown=5, fox=3, jumps=5
// Distinct sorted desc: [5, 3] → skip 1 → 3
7. Filter valid integers from strings¶
Filter out only the valid integers from a list of strings and store them in an Integer list.
public static List<Integer> filterValidIntegers(List<String> strings) {
return strings.stream()
.filter(s -> {
try {
Integer.parseInt(s.trim());
return true;
} catch (NumberFormatException e) {
return false;
}
})
.map(s -> Integer.parseInt(s.trim()))
.collect(Collectors.toList());
}
// Test
List<String> mixed = Arrays.asList("10", "abc", "20", "xyz", "30", "12.5", "");
System.out.println(filterValidIntegers(mixed)); // [10, 20, 30]
8. Words with maximum vowels¶
Given a string, find the words with the maximum number of vowels.
public static List<String> wordsWithMaxVowels(String sentence, int maxVowels) {
return Arrays.stream(sentence.split("\\s+"))
.filter(word -> countVowels(word) == maxVowels)
.collect(Collectors.toList());
}
private static long countVowels(String word) {
return word.chars()
.mapToObj(c -> (char) c)
.filter(c -> "aeiouAEIOU".indexOf(c) >= 0)
.count();
}
// Test
String input = "The quick brown fox jumps right over the little lazy dog";
// Vowels: The=1, quick=2, brown=1, fox=1, jumps=1, right=1, over=2, the=1, little=2, lazy=1, dog=1
System.out.println(wordsWithMaxVowels(input, 2)); // [quick, over, little]