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.

Leave a Reply