简体   繁体   中英

Convert String to List<Map<String, String>>> for tests

I need to convert a String to List<Map<String, String>>> for pass JUnit Test. I have this:

String userAttributes = "[{name=test, cp=458999, lastname=test2}]";

That i want is in the tests (Mockito) change a call to a server with this values, something like this:

Mockito.when(template.search(Mockito.anyString, new AttributesMapper()).thenReturn(attributes);

I need List<Map<String, String>>> for do this:

user.setUserName(attributes.get("name"));

Try regex or split by special char. First remove parentheses from beginning and end. After that you can split it by , and = to collect strings to map.

String userAttributes = "[{name=test, cp=458999, lastname=test2}]";

List<String> strings = Arrays.asList(userAttributes
      .replace("[{","").replace("}]","")
      .split(", "));
Map<String, String> collect = strings.stream()
      .map(s -> s.split("="))
      .collect(Collectors.toMap(s -> s[0], s -> s[1]));

System.out.println(collect.get("name"));

Other approach with Pattern

Map<String, String> collect = Pattern.compile(",")
        .splitAsStream(userAttributes
                .replace("[{","").replace("}]",""))
        .map(s -> s.split("="))
        .collect(Collectors.toMap(s -> s[0], s -> s[1]));

Or if you really wants use List<Map<String, String>>> . But after that you can not do this user.setUserName(attributes.get("name"));

List<Map<String, String>> maps = strings.stream()
      .map(s -> s.split("="))
      .map(s -> Map.of(s[0], s[1]))
      .collect(Collectors.toList());

System.out.println(maps);
    String userAttributes = "[{name=test, cp=458999, lastname=test2}]";
    StringTokenizer stringTokenizer = new StringTokenizer(userAttributes,",");
    List<Map<String,String>> list = new ArrayList<>();
    while(stringTokenizer.hasMoreElements()){
        StringTokenizer stringTokenizer2 = new StringTokenizer((String)stringTokenizer.nextElement(),"=");
        while(stringTokenizer2.hasMoreElements()){
            Map<String, String> map = new HashMap<>();
            map.put( ((String)stringTokenizer2.nextElement()),((String)stringTokenizer2.nextElement()) );
            list.add(map);
        }
    }

    System.err.println(list.toString());

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