java - 将字符串转换为列表
问题描述
我需要将 a 转换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"));
解决方案
尝试正则表达式或按特殊字符拆分。首先删除开头和结尾的括号。之后,您可以将其拆分,
并=
收集要映射的字符串。
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);
推荐阅读
- java - 从application.yml/java、spring中读取应用变量(assoc数组)
- python - 如何在 gurobi python 中四舍五入?
- r - 如何在 R 中按列有效地从数据表中采样?
- java - Spring Boot - java.sql.SQLIntegrityConstraintViolationException:无法添加或更新子行:外键约束失败
- sql-server - 递归查询“testtable”的“DataItem”列中的锚点和递归部分的类型不匹配
- airflow - 对 Airflow 的 BaseSensorOperator 参数感到困惑:超时、poke_interval 和模式
- discord - 如果找不到角色创建新角色 | 不和谐.js
- perl - Perl 中 Crypt::PBKDF2 中 HMACSHA2 哈希的大小是多少?
- r - 搜索快速变体以在巨大的矩阵(30000000 个元素)中查找单词的索引
- sql - 按列查询最后一个数据组