Convert a list Key Value to MultiLine and inverse in Java

3

From a list Map with structured key, value

Map<String, String> map = new LinkedHashMap<>();

map.put("param1","valor uno");
map.put("param2","valor dos");
map.put("param3","valor tres");

To convert a list to a string I use the toString method, to get the data sets separated by lines, I replace some characters of the return of the function toString

public static String mapToMultiLine(Map<String,String> map) {
  String str = map.toString().replace("{","").replace("}","").replace(", ","\n");
  return str;
}

Now I need to perform the inverse function multiLineToMap , meaning that from a string with a structure

param1=valor uno
param2=valor dos

param3=valor tres

Converts to a key value list (taking into account that if there is a blank line, delete it.

Update 1 , I have more or less something:

public static Map<String,String> multiLineToMap(String str ) {
    str = str.replaceAll("(?m)^[ \t]*\r?\n", ""); //eliminar lineas en blanco

    String lines[] = str.split("\n");

    //recorrer array lines
    //    separar key value, delimitador =
}
    
asked by Webserveis 02.05.2016 в 19:52
source

2 answers

2

Try something similar to the following passage:

// El mapa
Map<String, String> map = new LinkedHashMap<>();

// El texto de entrada
String input = "a=1\n\t\nb=2\nc=3=3";

// Remover líneas en blanco
input = input.replaceAll("(\r?\n)([ \t]*\r?\n)*", "$1");

// Utilizar la expresión regular (.*?)=(.*)
Matcher matcher = Pattern.compile("(.*?)=(.*)").matcher(input);
while (matcher.find()) {
    map.put(matcher.group(1), matcher.group(2));
}

// Opcionalmente comerte un pay ;-)
    
answered by 02.05.2016 / 20:44
source
2

If anyone is interested I have adapted the @Paul_Vargas code to the function multiLineToMap

public static Map<String,String> multiLineToMap(String input  ) {

    Map<String, String> map = new LinkedHashMap<>();

    // Remover líneas en blanco
    input = input.replaceAll("(\r?\n)([ \t]*\r?\n)*", "$1");

    Matcher matcher = Pattern.compile("(.*?)=(.*)").matcher(input);
    while (matcher.find()) {
        map.put(matcher.group(1), matcher.group(2));
    }

    return map;
}

Test the functions:

    String test = "param1=valor uno\nparam2=valor dos\n\nparam3=valor tres";

    System.out.println(mapToMultiLine(multiLineToMap(test)));

The output is as follows:

param1=valor uno
param2=valor dos
param3=valor tres
    
answered by 02.05.2016 в 20:54