[英]Convert String to List of Map
我有一个以下字符串。 我想将其转换为 Map 列表如下,
String esConnectionPropertiesStr = "ID1, 701, REST, 0, $PROJECT_ID),\n" +
"ID2, 702, ES_USERNAME, 0, $PROJECT_ID),\n" +
"ID3, 703, ES_PASSWORD, 0, $PROJECT_ID),\n" +
"ID4, 704, ES_HOST, 0, $PROJECT_ID";
Output:
[
{1=ID1, 2=701, 3= ES_USERNAME, 4= 0, 5= $PROJECT_ID},
{1=ID2, 2=702, 3= ES_PASSWORD, 4= 0, 5= $PROJECT_ID},
{1=ID3, 2=703, 3=ES_HOST, 4= 0, 5= $PROJECT_ID},
{1=ID4, 2=704, 3= ES_PORT, 4= 0, 5=$PROJECT_ID}
]
它由),
分割,然后由逗号分割以获得 map 元素。 我尝试了以下哪些有效,
AtomicInteger index = new AtomicInteger(0);
Arrays.stream(esConnectionPropertiesStr.split("\\),"))
.map(e -> Arrays.stream(e.split(","))
.collect(Collectors.toMap(n1 -> index.incrementAndGet(), s -> s)))
.peek(i -> index.set(0))
.collect(Collectors.toList());
有没有更好的方法来做到这一点?
AtomicInteger
在这里是多余的。 它增加了更多的复杂性和更多的失败空间。 此外, Stream API
的规范不保证Stream::peek
的执行。
这是天真的(虽然很长)的解决方案:
List<Map<Integer, String>> resultMap =
Arrays.stream(esConnectionPropertiesStr.split("\\),"))
.map(row -> Arrays.stream(row.split(","))
.collect(collectingAndThen(toList(),
list ->IntStream.range(0, list.size())
.boxed()
.collect(toMap(identity(), list::get)))))
.collect(toList());
尽管上述解决方案有效,但恕我直言,它不可读。 我会将list-to-map
转换提取为 static util 方法:
class Utils { //
public static Map<Integer, String> toIndexedMap(List<String> list) {
return IntStream.range(0, list.size())
.boxed()
.collect(toMap(identity(), list::get));
}
然后使用以下实用方法:
List<Map<Integer, String>> result =
Arrays.stream(esConnectionPropertiesStr.split("\\),"))
.map(row -> Arrays.stream(row.split(","))
.collect(collectingAndThen(toList(), Utils::toIndexedMap)))
.collect(toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.