簡體   English   中英

將字符串轉換為列表<map<string, string> &gt;&gt; 用於測試</map<string,>

[英]Convert String to List<Map<String, String>>> for tests

我需要將String轉換為List<Map<String, String>>>以通過 JUnit 測試。 我有這個:

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

我想要的是在測試(Mockito)中更改對具有此值的服務器的調用,如下所示:

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

我需要List<Map<String, String>>>來做到這一點:

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

嘗試正則表達式或按特殊字符拆分。 首先刪除開頭和結尾的括號。 之后,您可以將其拆分為,=以將字符串收集到 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"));

Pattern的其他方法

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

或者,如果您真的想使用List<Map<String, String>>> 但在那之后你不能這樣做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());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM