Skip to content

User-Defined Customer Interface (Exercise Problem)

This is an exercise problem for your practice. Try to come up with an approach and solve it by yourself. Good Luck!

Gopi Gorantala
Gopi Gorantala
1 min read

Table of Contents

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);
  }
}
Java

Gopi Gorantala Twitter

Gopi is a highly experienced Full Stack developer with a deep understanding of Java, Microservices, and React. He worked in India & Europe for startups, the EU government, and tech giants.

Comments


Related Posts

Members Public

How To Write Lambda Expressions

This lesson introduces the basic lambda expression structure with tips to write efficient code.

Members Public

What Are Lambda Expressions?

This is an introductory lesson on lambda expressions. You will learn about the lambda operator, expression, syntaxes and more!

Members Public

Power Of Two (Exercise Problem)

This is an exercise problem for your practice. Try to come up with an approach and solve it by yourself. Good Luck!