Java String to Map stringToMap(String src)

Here you can find the source of stringToMap(String src)

Description

Converts a name-value pair string into a Map object.

License

Open Source License

Parameter

Parameter Description
src String containing name-value pairs.

Return

resulting Map object; will be empty if the string was null or empty.

Declaration

public static HashMap stringToMap(String src) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.HashMap;

public class Main {
    /**//  w w w.  j ava 2  s  . c  o m
     * Converts a name-value pair string into a Map object.
     *
     * @param src String containing name-value pairs.
     * @return resulting Map object; will be empty if the string was null or
     *         empty.
     */
    public static HashMap stringToMap(String src) {
        HashMap<String, String> dest = new HashMap<String, String>();

        if (src == null) {
            return (dest);
        }

        String line, key, val;
        int equalsPos, newLinePos, startPos = 0, len = src.length();
        while (startPos < len) {
            newLinePos = src.indexOf('\n', startPos);

            // if the last line does not end with a newline character,
            // assume an imaginary newline character at the end of the string
            if (newLinePos == -1) {
                newLinePos = len;
            }

            line = src.substring(startPos, newLinePos);

            equalsPos = line.indexOf('=');
            if (equalsPos != -1) {
                key = line.substring(0, equalsPos);
                val = line.substring(equalsPos + 1);
            } else {
                key = line;
                val = null;
            }

            dest.put(key, val);

            startPos = newLinePos + 1;
        }

        return (dest);
    }
}

Related

  1. stringToCharMap(String s)
  2. stringToMap(final String s)
  3. stringToMap(final String s)
  4. stringToMap(String append)
  5. stringToMap(String source, String delimiter)
  6. stringToMap(String src)
  7. StringToMap(String str)
  8. stringToMap(String str)
  9. stringToMap(String value)