Unlocking Success with Java Stream API
Gurunath Kadam
Strategic Manager of Learning & Development | Subject Matter Expert | Oracle & Microsoft Certified | Educator | Software Developer | Corporate Trainer | Technical Speaker
In today's Java ecosystem, proficiency in the Stream API is paramount. Whether for interviews or real-world projects, mastering Java streams elevates skills and opens new avenues.
Java Stream API questions are ubiquitous in technical interviews, gauging candidates' problem-solving prowess and understanding of functional programming. Proficiency signals efficiency in data processing and Java library utilization, setting candidates apart.
Java streams are integral in software projects, offering powerful data manipulation tools. They enable efficient data processing, cleaner code, and improved performance, making them indispensable in web apps, data pipelines, and backend systems.
Mastering Java streams is a gateway to success, enhancing both interview performance and project outcomes. Embrace Java streams to unlock new heights in your development journey.
Here, we've curated a series of Java Stream coding interview questions to help you hone your skills and excel in your coding interviews:
Q1. Find the longest string in a list of strings using Java streams:
?List<String> strings = Arrays
????????????? .asList("apple", "banana", "cherry", "date", "grapefruit");
Optional<String> longestString = strings
????????????? .stream()
????????????? .max(Comparator.comparingInt(String::length));
Q2. Calculate the average age of a list of Person objects using Java streams:
?List<Person> persons = Arrays.asList(
??? new Person("Alice", 25),
??? new Person("Bob", 30),
??? new Person("Charlie", 35)
);
double averageAge = persons.stream()
????????????????????????? .mapToInt(Person::getAge)
????????????????????????? .average()
????????????????????????? .orElse(0);
Q3. Check if a list of integers contains a prime number using Java streams:
?public boolean isPrime(int number) {
? if (number <= 1) {
??? return false;
? }
? for (int i = 2; i <= Math.sqrt(number); i++) {
??? if (number % i == 0) {
??????? return false;
??? }
? }
? return true;
}
?private void printPrime() {
? List<Integer> numbers = Arrays.asList(2, 4, 6, 8, 10, 11, 12, 13, 14, 15);
? boolean containsPrime = numbers.stream()
???????????????????????????????? .anyMatch(this::isPrime);
? System.out.println("List contains a prime number: " + containsPrime);
??}
Q4. Merge two sorted lists into a single sorted list using Java streams:
?List<Integer> list1 = Arrays.asList(1, 3, 5, 7, 9);
List<Integer> list2 = Arrays.asList(2, 4, 6, 8, 10);
List<Integer> mergedList = Stream.concat(list1.stream(), list2.stream())
??????????????????????????????? .sorted()
??????????????????????????????? .collect(Collectors.toList());
Q5. Find the intersection of two lists using Java streams:
?List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> list2 = Arrays.asList(3, 4, 5, 6, 7);
List<Integer> intersection = list1.stream()
????????????????????????????????? .filter(list2::contains)
????????????????????????????????? .collect(Collectors.toList());
Q6. Remove duplicates from a list while preserving the order using Java streams:
?List<Integer> numbersWithDuplicates = Arrays.asList(1, 2, 3, 2, 4, 1, 5, 6, 5);
List<Integer> uniqueNumbers = numbersWithDuplicates
?????????????????????????????????????? .stream()
?????????????????????????????????????? .distinct()
?????????????????????????????????????? .collect(Collectors.toList());
Q7. Given a list of transactions, find the sum of transaction amounts for each day using Java streams:
?List<Transaction> transactions = Arrays.asList(
??? new Transaction("2022-01-01", 100),
??? new Transaction("2022-01-01", 200),
??? new Transaction("2022-01-02", 300),
??? new Transaction("2022-01-02", 400),
??? new Transaction("2022-01-03", 500)
);
?Map<String, Integer> sumByDay = transactions
??????????????????????? .stream()
??????????????????????? .collect(Collectors.groupingBy(Transaction::getDate,
?????????????????????????????? Collectors.summingInt(Transaction::getAmount)));
Q8. Find the kth smallest element in an array using Java streams:
?int[] array = {4, 2, 7, 1, 5, 3, 6};
int k = 3; // Find the 3rd smallest element
int kthSmallest = Arrays.stream(array)
?????????????????????? .sorted()
?????????????????????? .skip(k - 1)
?????????????????????? .findFirst()
?????????????????????? .orElse(-1);
Q9. Given a list of strings, find the frequency of each word using Java streams:
?List<String> words = Arrays.asList("apple", "banana", "apple", "cherry",
??????????????????????????????????? "banana", "apple");
Map<String, Long> wordFrequency = words
????????????? .stream()
????????????? .collect(Collectors
??????????????????? .groupingBy(Function.identity(), Collectors.counting())
??????????????? );
Q10. Implement a method to partition a list into two groups based on a predicate using Java streams:
?List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
Map<Boolean, List<Integer>> partitioned = numbers
??????????????????????? .stream()
??????????????????????? .collect(Collectors.partitioningBy(n -> n % 2 == 0));
List<Integer> evenNumbers = partitioned.get(true);
List<Integer> oddNumbers = partitioned.get(false);
System.out.println("Even numbers: " + evenNumbers);
System.out.println("Odd numbers: " + oddNumbers);
?Q11. Implement a method to calculate the Fibonacci sequence using Java streams:
?Stream<Long> fibonacci = Stream.iterate(
??????????????????? new long[]{0, 1}, f -> new long[]{f[1], f[0] + f[1]})
???????????????? .mapToLong(f -> f[0]);
// Print first 10 Fibonacci numbers
fibonacci.limit(10).forEach(System.out::println);
Q12. Find the median of a list of integers using Java streams:
?List<Integer> numbers = Arrays.asList(5, 2, 1, 3, 4);
OptionalDouble median = numbers.stream()
?????????????????????????????? .sorted()
?????????????????????????????? .mapToInt(Integer::intValue)
?????????????????????????????? .collect(IntStatistics.summaryStatistics())
?????????????????????????????? .getMedian();
System.out.println("Median: " + median.getAsDouble());
Q13. Given a list of strings, find the longest common prefix using Java streams:
?List<String> strings = Arrays.asList("flower", "flow", "flight");
String longestCommonPrefix = strings.stream()
?????????????????? .reduce((s1, s2) -> {
?????????????????????? int length = Math.min(s1.length(), s2.length());
?????????????????????? int i = 0;
?????????????????????? while (i < length && s1.charAt(i) == s2.charAt(i)) {
?????????????????????????? i++;
?????????????????????? }
?????????????????????? return s1.substring(0, i);
?????????????????? })
?????????????????? .orElse("");
System.out.println("Longest common prefix: " + longestCommonPrefix);
Q14. Find the maximum product of two integers in an array using Java streams:
?int[] array = {1, 4, 3, 6, 2, 7, 8};
int maxProduct = IntStream.range(0, array.length)
????????????????????? .mapToObj(i -> IntStream.range(i + 1, array.length)
????????????????????????????????????????????? .map(j -> array[i] * array[j])
????????????????????????????????????????????? .max()
????????????????????????????????????????????? .orElse(Integer.MIN_VALUE))
????????????????????? .max(Integer::compare)
????????????????????? .orElse(Integer.MIN_VALUE);
System.out.println("Maximum product: " + maxProduct);
Q15. Implement a method to find all anagrams in a list of strings using Java streams:
?List<String> words = Arrays.asList("listen", "silent", "hello",
?????????????????????????????????? "world", "night", "thing");
Map<String, List<String>> anagrams = words.stream()
?????????????????????????????????? .collect(Collectors.groupingBy(str -> {
?????????????????????????????????????? char[] chars = str.toCharArray();
?????????????????????????????????????? Arrays.sort(chars);
?????????????????????????????????????? return new String(chars);
?????????????????????????????????? }));
System.out.println("Anagrams: " + anagrams);
Q16. Given a list of intervals, find the total covered length using Java streams:
?List<Interval> intervals = Arrays.asList(new Interval(1, 3),
?????????????????? new Interval(5, 8), new Interval(10, 12));
int totalCoveredLength = intervals.stream()
???????????? .mapToInt(interval -> interval.getEnd() - interval.getStart())
???????????? .sum();
System.out.println("Total covered length: " + totalCoveredLength);
Q17. Find the number of occurrences of a given character in a list of strings using Java streams:
?List<String> strings = Arrays.asList("apple", "banana", "orange",
??????????????????????????????????? "grape", "melon");
char target = 'a';
long occurrences = strings.stream()
???????????????????????? .flatMapToInt(CharSequence::chars)
???????????????????????? .filter(c -> c == target)
???????????????????????? .count();
System.out.println("Occurrences of '" + target + "': " + occurrences);
Q18. Given a list of integers, find all pairs of numbers that sum up to a given target using Java streams:
?List<Integer> numbers = Arrays.asList(2, 4, 6, 8, 10);
int target = 12;
Set<String> pairs = numbers.stream()
????? .flatMap(i -> numbers.stream().
??????????????????? map(j -> i + j == target ? "(" + i + ", " + j + ")" : ""))
????? .filter(s -> !s.isEmpty())
????? .collect(Collectors.toSet());
System.out.println("Pairs that sum up to " + target + ": " + pairs);
Q19. Given a list of integers, find all non duplicate integers using Java streams:
?List<Integer> numbers = Arrays.asList(1, 2, 3, 2, 4, 5, 6, 4, 7, 8, 9, 9);
?// Count the occurrences of each number
Map<Integer, Long> frequencyMap = numbers.stream()
??????? .collect(Collectors
????????????? .groupingBy(Function.identity(), Collectors.counting())
???????? );
?
// Filter out non-duplicate numbers
??????? .filter(number -> frequencyMap.get(number) == 1)
??????? .forEach(System.out::println);
Q20. Given a list of strings, find the longest string using Java streams.
?List<String> strings = Arrays.asList("apple", "banana", "orange",
???????????????????????????????????? "grape", "kiwi");
?
String longestString = strings.stream()
??????? .max((s1, s2) -> Integer.compare(s1.length(), s2.length()))
??????? .orElse(null);
Q21. How do you create a stream of random numbers in Java?
You can create a stream of random numbers in Java using the Random class along with the Stream.generate method. For example:
?Random random = new Random();
Stream<Integer> randomNumbers = Stream.generate(random::nextInt);
Q22. How do you perform grouping and aggregation operations on Java streams?
?Grouping and aggregation operations on Java streams can be performed using the Collectors.groupingBy and Collectors.summarizingInt (or similar) collectors. These collectors allow you to group elements based on certain criteria and perform aggregation operations like sum, average, count, etc. For example:
?List<String> names = Arrays.asList("John", "Alice", "Bob", "Jane");
Map<Integer, Long> countByNameLength = names
????? .stream()
????? .collect(Collectors.groupingBy(String::length, Collectors.counting()));
Q23. How do you handle null values in Java streams?
?If you’re applying functions to stream elements that may return null, you should handle null values explicitly within the function to avoid NullPointerExceptions.
?List<String> list = Arrays.asList("apple", null, "banana", null, "orange");
List<String> filteredList = list.stream()
?????????????????????????????? .map(s -> {
?????????????????????????????????? if (s == null) {
?????????????????????????????????????? return "N/A";
?????????????????????????????????? }
?????????????????????????????????? // Perform other operations
?????????????????????????????????? return s.toUpperCase();
?????????????????????????????? })
?????????????????????????????? .collect(Collectors.toList());
If you’re dealing with methods that may return null, you can wrap the values in an Optional to handle null values more gracefully.
?List<String> list = Arrays.asList("apple", null, "banana", null, "orange");
List<Optional<String>> optionalList = list.stream()
????????????????????????????????????????? .map(Optional::ofNullable)
????????????????????????????????????????? .collect(Collectors.toList());
You can use the filter method to remove null values from the stream before performing further operations. This ensures that downstream operations won't encounter null values.
?List<String> list = Arrays.asList("apple", null, "banana", null, "orange");
List<String> nonNullList = list.stream()
????????????????????????????? .filter(Objects::nonNull)
????????????????????????????? .collect(Collectors.toList());
Conclusion:
Mastering Java streams opens up a world of possibilities for efficient data processing and problem-solving. In this example, we've seen how Java streams simplify the task of finding the longest string in a list, demonstrating the power and elegance of functional programming.
?By embracing Java streams, you not only enhance your coding proficiency but also streamline your development process. Whether you're preparing for technical interviews or tackling real-world projects, Java streams are your go-to tool for writing cleaner, more concise code and unlocking new levels of productivity.
?Continue exploring Java streams and incorporating them into your projects to stay ahead in the ever-evolving world of Java development. With Java streams at your fingertips, there's no limit to what you can achieve. Keep coding, keep streaming, and let your Java skills soar!
Java Full Stack Development Trainer
10 个月Thank you so much Gurunath, it is a really too good article for understanding java 8 Stream API.
Ex- java developer intern at cyperts digital solutions Pvt Ltd | software Developer | java | spring boot | micorservices | SQL | CSS | HTML.
10 个月This is a great resource for Java Stream interview questions. It's perfect for developers looking to improve their problem-solving skills. #JavaStreamMastery #CareerGrowth
Ex- java developer intern at cyperts digital solutions Pvt Ltd | software Developer | java | spring boot | micorservices | SQL | CSS | HTML.
11 个月Great resource for Java Stream interview questions! This will definitely help developers prepare for technical interviews and improve their problem-solving skills. #JavaStreamMastery #CareerGrowth
Founder & Managing Director
11 个月Thanks for sharing. Valuable resource
Java Full Stack Trainer | Corporate trainer
11 个月Thank you for sharing. This is very helpful.