Java learning: using Map to replace numerous if-else and mapif-else

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.