Java learning: using Map to replace numerous if-else and mapif-else
#2014.11.13 #
Problem scenario: process the string according to the tag. Input Format: {tag} {target string}
Capitalized String1 lowercase String2 reverse String3 .... functionN StringN generally uses the if else implementation method as follows: while (read row) {splits the input of each row, and then stores the String function, String str; if (function. equals ("capitalized") {// call function to process str} else if (function. equals ("lowercase") {// call the function to process str} else if (){}...} this is not easy to write and the code is ugly. The Map ing capability can solve this problem. The basic idea is to use Map to establish a ing relationship with the corresponding <class>, in this case, Map. get (<tag>) is the class. Call the method to solve the problem of Map. get (<tag> ). getResult (str); Implementation Method: first define an interface public interface Type {String getResult (String str );} next, inherit this interface to implement various functional classes: public class functionA implements Type {@ Override public String getResult (String str) {// function of function }}..... same functionB, functionC ...... the above are some preparations. The first part of if-else Is converted as follows: Map <String, Type> map = new HashMap <String, Type> (); map. put ("capitalized", new functionA (); map. put ("lowercase", new functionB (); map. put ("backward", new functionC ());....... while (read row) {splits the input of each row and stores it in String function, String str; map. get (function ). getResult (str );}