adding multiple entries to a HashMap at once in one statement

前端 未结 9 968
迷失自我
迷失自我 2020-12-04 06:27

I need to initialize a constant HashMap and would like to do it in one line statement. Avoiding sth like this:

  hashMap.put(\"One\", new Integer(1)); // add         


        
9条回答
  •  借酒劲吻你
    2020-12-04 06:34

    Another approach may be writing special function to extract all elements values from one string by regular-expression:

    import java.util.HashMap;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Example {
        public static void main (String[] args){
            HashMap hashMapStringInteger = createHashMapStringIntegerInOneStat("'one' => '1', 'two' => '2' , 'three'=>'3'  ");
    
            System.out.println(hashMapStringInteger); // {one=1, two=2, three=3}
        }
    
        private static HashMap createHashMapStringIntegerInOneStat(String str) {
            HashMap returnVar = new HashMap();
    
            String currentStr = str;
            Pattern pattern1 = Pattern.compile("^\\s*'([^']*)'\\s*=\\s*>\\s*'([^']*)'\\s*,?\\s*(.*)$");
    
            // Parse all elements in the given string.
            boolean thereIsMore = true;
            while (thereIsMore){
                Matcher matcher = pattern1.matcher(currentStr);
                if (matcher.find()) {
                    returnVar.put(matcher.group(1),Integer.valueOf(matcher.group(2)));
                    currentStr = matcher.group(3);
                }
                else{
                    thereIsMore = false;
                }
            }
    
            // Validate that all elements in the given string were parsed properly
            if (currentStr.length() > 0){
                System.out.println("WARNING: Problematic string format. given String: " + str);
            }
    
            return returnVar;
        }
    }
    

提交回复
热议问题