简体   繁体   English

将字符串转换为 Map 列表

[英]Convert String to List of Map

I have a following String.我有一个以下字符串。 I want to convert it into List of Map as below,我想将其转换为 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: 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} 
]

It is spliting by ), and then by comma to get map elements.它由),分割,然后由逗号分割以获得 map 元素。 I tried following which works,我尝试了以下哪些有效,

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());

Is there any better way to do this??有没有更好的方法来做到这一点?

The AtomicInteger is redundant here. AtomicInteger在这里是多余的。 It adds more complexity and more room for failure.它增加了更多的复杂性和更多的失败空间。 Moreover the specification of Stream API does not guarantee the execution of Stream::peek .此外, Stream API的规范不保证Stream::peek的执行。

This is the naive (though pretty long) solution:这是天真的(虽然很长)的解决方案:

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());

Although the solution above works, IMHO it isn't readable.尽管上述解决方案有效,但恕我直言,它不可读。 I would extract the list-to-map conversion into a static util method:我会将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));
}

then use the utility methods as follow:然后使用以下实用方法:

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.

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