User-Defined Customer Interface (Exercise Problem)
1 min readThis is an exercise problem for your practice. Try to come up with an approach and solve it by yourself. Good Luck!
Introduction
Given an array of strings, with the help of the Consumer interface applies some string operations.
Problem Statement
Write a program to capital case all the lists of fruits using the Consumer interface.
Input = {"apple", "orange", "Guava", "mango", "banana", "kiwi"}
Output = {"APPLE", "ORANGE", "GUAVA", "MANGO", "BANANA", "KIWI"}Thought process
This is a simple problem asking us to capitalize each string and print them. To do string operations on all of the strings in the list, we need to iterate over all of the strings and apply String operations.
As we are iterating over the entire list, the time complexity or the time taken to run our algorithm is directly proportional to O(n), where n is the number of strings present in the list.
Note: O(n) is usually read as Order of n, which is linear. This is a term we use in software to determine the time taken by an algorithm to solve a problem (Big-O complexity analysis).Coding exercise
import java.util.function.Consumer;
class ConsumerImpl implements Consumer<String> {
@Override
public void accept(String str) {
// WRITE-YOUR-CODE-HERE
}
}Now, try to come up with an approach. This problem is designed for your practice, so try to solve it yourself first. If you get stuck, you can always refer to the solution below. Good luck!
Hint: Go back to Consumer interface and read through the topic to understand steps to implement it.First, look at these code snippets below and think of a solution.
The solution will be explained below.
import java.util.function.Consumer;
class ConsumerImpl implements Consumer<String> {
@Override
public void accept(String str) {
System.out.println(str.toUpperCase());
}
}import java.util.function.Consumer;
import src.dev.ggorantala.constants.Constants;
class Solution {
public static void main(String[] args) {
Consumer<String> fruitsConsumer = new ConsumerImpl();
Constants.FRUITS_LIST.forEach(fruitsConsumer);
}
}