Home > Mobile >  Covert if else statement to hasmap in JAVA
Covert if else statement to hasmap in JAVA

Time:08-20

I want to implement a function in java that gets string input and process it. Here is how i implement it using if else statement:

class Main {
    static String string_process(String s_in) {
        String s_out;
        if(s_in.contains("USA")){
            s_out = "english";
        }
        else if(s_in.contains("Germany")){
            s_out = "dutch";
        }
        else if(s_in.contains("Brazil")){
            s_out = "Portuguese";
        }
        else {
            s_out = "Uknown";
        }
        return s_out;
    }

    public static void main(String[] args) {
        String process = string_process("I am from USA!");
        System.out.println("I understand " process);
    }
}

I'm wondering if i can implement it hashmap. Is there any benefit of doing so in terms of complexity?

CodePudding user response:

The benefit is that it requires less code to handle the cases and to add a new case.

This is what it looks like with a map:

class Main {
    static Map<String, String> countryToLanguageMap = Map.of(
        "USA", "english",
        "Germany", "dutch",
        "Brazil", "Portuguese"
    );

    static String string_process(String s_in) {
        for (Map.Entry<String, String> entry : countryToLanguageMap.entrySet()) {
            if(s_in.contains(entry.getKey())){
                return entry.getValue();
            }
        }
        return "Unknown";
    }

    public static void main(String[] args) {
        String process = string_process("I am from USA!");
        System.out.println("I understand " process);
    }
}

For example, let's suppose you want to add a new case, "UK" with "english". This is what you would have to add with the map-based version:

        ...
        "UK", "english",
        ...

while with the original version:

     ...
     else if(s_in.contains("UK")){
            s_out = "english";
     }
     ...

CodePudding user response:

In short it would make the code more readable but it the runtime complexity would not change in a notable capacity. Like the other answers you would need to make a global hash-map variable to hold the key-value pairs.

CodePudding user response:

Here's a possible solution using Stream API and static Map.

Note: names like string_process() are not aligned with Java naming convention and doesn't provide much information to the reader about its purpose.

Basically solution boils down to a combination of methods filter() findFirst(), which produces an Optianal. In case if optional is empty, default value "Unknown" would be provided as a result.

private static final Map<String, String> COUNTRY_BY_LANGUAGE =
    Map.of("USA", "English", "Germany", "German", "Brazil", "Portuguese");
public static String processCountry(String from) {
    
    return COUNTRY_BY_LANGUAGE.entrySet().stream()
        .filter(entry -> entry.getKey().contains(from))
        .findFirst()
        .map(Map.Entry::getValue)
        .orElse("Unknown");
}

CodePudding user response:

Simple brute-force solution without sophisticated algorithms would be:

  • build your HashMap
  • Loop through keys in hashMap, using 'indexOf' method of String checking if index >= 0 That would be n*k time complexity (n - keyword count, k - Average input string length)
public class Solution {

    private static final Map<String, String> COUNTRY_TO_LANGUAGE = Map.of(
            "USA", "English",
            "Germany", "Deutsch", 
            "Brazil", "Portuguese");
    private static final String UNKNOWN = "Unknown";

    public static String find(String greeting) {
        for(String key: COUNTRY_TO_LANGUAGE.keySet()) {
            if (greeting.indexOf(key) >= 0) return COUNTRY_TO_LANGUAGE.get(key);
        }
        return UNKNOWN;
    }

    public static void main(String[] args) {
        String greeting = "I am from USA!";
        System.out.println("I understand "   find(greeting));
    }
}

So instead of adding new if-else block you just update your map.

  • Related