Java Interview Practice Problem (Beginner): Bag of Fruits
Post last modified:January 26, 2023
Reading time:4 mins read
Solving with Imperative and functional styles both
Problem Statement
We have been given a bag of fruits. We need to find all the fruits that are more than the given threshold.
For example, the list of the below fruits contains 3 types of fruits and each with a different occurrence, apple →6, grapes →2, kiwi →5, so the answer is apple and kiwi since their count is more than 2
Solution
We will solve this problem with Imperative style and functional style
Prior Java8 (Imperative Style)
At first, we need key-value pair, where we can keep the name of the fruits and the occurrence of the fruits. In Java, we will initialize HashMap for this.
We will iterate over each fruit over the list of the fruits using external iterators and fruit to hash key, for the value we can if we have already added this key before if yes then we get the value and increment with 1 otherwise if this is the first time then we get 0 and add 1 for current occurrence.
getorDefault method mainly gets the value of the key if present or gives a default value which is 0 in this case.
Now we have map of fruit → count , for example [ apple → 6, kiwi →5, grapes → 2 ]
The next step is to iterate over this and filter all the pairs with a count greater than the threshold ( 2 in this case).
Again we use an external iterator to traverse the map. The map provides an entrySet method that returns the Entry instance. we can getKey and getValue over Entry.
We check if the value of the key is greater than the threshold, if yes then we add them to the result in the list defined before for the loop.
Once the loop is finished, we convert our list to string and print it.
Let’s try to solve it using java8 functional programming.
With Java8
We stream over our fruits list and collect them into the map, we apply to count over each element in the list and group them using groupBy.
Now we have map of fruit → count , for example [ apple → 6, kiwi →5, grapes → 2 ]
We can get entrySet() over the map then stream over it and filter all the entry set where the value is greater than the threshold. For each filtered entryset we only get the key (fruit name) and finally add them to String Array.
Now our result consists of a String array, we can convert it to string and print
Entire code
package Easy;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class BagOfFruits {
// give bag of fruit boxes , find fruits whose count more than 2
static List<String> fruits = List.of("apple",
"apple","apple","apple", "apple", "apple",
"grapes", "grapes",
"kiwi","kiwi", "kiwi", "kiwi", "kiwi");
static long THRESHOLD = 2;
// output : [apple, kiwi]
public static void main(String[] args) {
priorJava8();
java8Style();
}
private static void priorJava8(){
Map<String, Integer> countingMap = new HashMap<>();
for(String fruit: fruits){
countingMap.put(fruit, countingMap.getOrDefault(fruit, 0)+1);
}
List<String> result = new ArrayList<>();
for(Map.Entry<String, Integer> fruitCountMap : countingMap.entrySet()){
if(fruitCountMap.getValue()>THRESHOLD){
result.add(fruitCountMap.getKey());
}
}
System.out.println("Before java 8");
System.out.println(result.toString());
}
private static void java8Style() {
Map<String, Long> countingMap = fruits.stream()
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
String[] result = countingMap.entrySet()
.stream()
.filter(a -> a.getValue() > THRESHOLD)
.map(Map.Entry::getKey)
.toArray(String[]::new);
System.out.println("After java 8");
System.out.println(Arrays.toString(result));
}
}
Conclusion
We used the Imperative style and declarative style( functional programming ) to solve simple counting problems.
If you found another solution, please add to the comment for others.
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
Cookie
Duration
Description
cookielawinfo-checkbox-analytics
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional
11 months
The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy
11 months
The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.