JAVA STREAM API PROGRAMS
In this document you will get some problem-based program in JAVA and detailed code
for the same. Before starting with this one you should have cleared the basic concept of
JAVA 8 Stream concepts in order to understand the solution.
You can refer to the document below to get the basic knowledge of JAVA in one place.
Happy learning. Keep learning!!!!!
Question 1: You are given a list of fruit names where some fruits appear multiple times.
Write a Java program that uses the Stream API to count the number of occurrences of
each fruit in the list and prints the result in the form of a map, where the keys are the
fruit names, and the values are the corresponding counts.
Example Input: ["Apple", "Banana", "Apple", "Grapes", "Banana", "Orange", "Apple"]
Expected Output: {Apple=3, Banana=2, Grapes=1, Orange=1}
Solution:
Code Breakdown:
[Link](): Converts the list into a stream for processing.
groupingBy(fruit -> fruit): Groups the fruits based on their name.
[Link](): For each group (each fruit), counts the number of
occurrences.
Question 2: Given a string, write a Java program that finds the most frequent character
in the string using the Stream API. If multiple characters have the same highest
frequency, return any one of them. If the string is empty, handle the case appropriately.
Example Input: "success"
Expected Output: Most frequent character: 's'
Solution:
Code Breakdown:
[Link]().stream(): This converts the map of character
frequencies into a stream of [Link] objects.
.max([Link]()): This finds the [Link] with the highest
value (i.e., the character that occurs the most).
.get().getKey(): This retrieves the key (character) from the entry with the highest
frequency.
Question 3: Write a Java program to check if two strings are anagrams of each other.
Two strings are considered anagrams if they contain the same characters in any order
and have the same length. The program should use Java Streams to solve the problem.
Example Input:
String str1 = "listen";
String str2 = "silent";
Expected Output: Are the two strings anagrams? true
Solution:
Code Breakdown:
[Link]() converts the string str1 into an IntStream of character code points
(since chars() returns an IntStream).
.sorted() sorts the characters in ascending order.
.boxed() converts the IntStream into a Stream<Integer> by wrapping the
primitive int values into Integer objects.
.collect([Link]()): This collects the sorted characters from the stream
into a list.
.equals() compares the two lists for equality.
Question 4:
Write a Java program that takes a string as input and returns a string containing all the
distinct characters from the input, preserving the order of their first appearance. Use
Java Streams to solve the problem.
Example Input: hello world
Expected Output: "helo wrd"
Solution:
Code Breakdown:
The chars() method returns an IntStream of Unicode values representing the
characters in the string.
the distinct() method ensures that only unique characters from the stream are
kept, removing any duplicates.
mapToObj() converts each int value (character's Unicode code point) back into its
corresponding Character object. Here, it is converted into a String object using
[Link]().
collects the distinct characters and joins them into a single string using
[Link]()
Question 5:
Write a Java program that takes a list of integers and sorts them in ascending order
using Java Streams. The program should output the sorted list.
Example Input: [3, 66, 88, 22, 45]
Expected Output: [3, 22, 45, 66, 88]
Solution:
Code Breakdown:
[Link]() creates a stream from the list.
.sorted() sorts the stream elements in their natural order (ascending order for
integers).
.collect([Link]()) collects the sorted elements into a new list
(sortedList).
Question 6:
Write a Java program that sorts a list of employees based on their salary in ascending
order. If two employees have the same salary, they should be further sorted by their
department.
Solution:
Code Breakdown:
[Link](Employee::getSalary): Sorts the employees by salary in
ascending order.
.thenComparing(Employee::getDepartment): In case two employees have the
same salary, they are further sorted by the department.
Question 7: Given a list of employees with their salaries and departments, calculate the
average salary for each department.
Solution:
Code Breakdown:
groupingBy(): Groups the employees by department.
averagingDouble(): Computes the average salary for each group.
Question 8: Write a Java program that takes a list of integers and calculates the sum of
all even numbers in that list using Java Streams.
Example Input: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Expected Output: 3
Solution:
Code Breakdown:
The filter() method is used to retain only those numbers that are even. The
condition n % 2 == 0 checks if a number is even.
The mapToInt() method converts the stream of Integer objects into an IntStream
of primitive int values. This is necessary for using the sum() method.
The sum() method calculates the total sum of all the integers in the IntStream
Question 9: Write a Java program that takes a list of lists (a nested list) and flattens it
into a single list containing all the elements from the inner lists.
Solution:
Code Breakdown:
The flatMap() method is applied to the stream of lists. For each inner list, it
creates a stream of its elements, effectively flattening the nested structure into a
single stream of integers.
Question 10: Given a list of strings, find the longest word(s) in the list. If there are
multiple longest words, return them all.
Solution:
Code Breakdown:
map(String::length): Maps each word in the stream to its length, transforming
the stream of words into a stream of integers (lengths).
max(Integer::compare): Finds the maximum value in the stream of lengths. This
returns an Optional<Integer> representing the maximum length found.
orElse(0): If no maximum length is found (in case the list is empty), it defaults to
0. This ensures that maxLength is always initialized to a valid integer.
filter(word -> [Link]() == maxLength): Filters the words to retain only
those whose length is equal to maxLength. This results in a stream of the longest
words.