简体   繁体   中英

How to get an HashMap<String,ArrayList<String>> from a given String Java

So I receive a String that contains a HashMap<String, ArrayList<String>> inside how do I debunk it till I get myself a new HashMap from that String .

This is the string :

String s= "{Lobby1=[John, Ana], Lobby2=[Tomas, Peter]}"  

Keep in mind the string can be longer depending on the number of entries or puts

This is what i did to get ride of the "{ }":

 s=s.substring(1,s.length()-1);

This gets me :

Lobby1=[John, Ana], Lobby2=[Tomas, Peter]

I don't know what to do now, how do I get an Arraylist and a String from that.

How about something like that:

private static final Pattern RE = Pattern.compile("^\\s*([^=\\[\\]]+)\\s*=\\s*\\[([^\\]]*)\\]\\s*(?:,(.*))?$");

public static void main(String args[]) {
    String s = "Lobby1=[John, Ana], Lobby2=[Tomas, Peter]";
    Map<String,List<String>> map = new HashMap<>();
    Matcher matcher = RE.matcher(s);
    while (matcher.matches()) {
        String name = matcher.group(1);
        List<String> list = Arrays.asList(
                matcher.group(2).split("\\s*,\\s*"));
        map.put(name, list);
        String tail = matcher.group(3);
        if (tail == null) {
            break;
        }
        matcher = RE.matcher(tail);
    }
    System.out.println(map);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM