将字符串转换为地图列表

Code_Mode:

我有以下字符串。我想将其转换为下面的地图列表,

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";

输出:

[ 
    {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} 
]

),先用逗号分割,然后再得到逗号。我尝试了下面的方法,

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

有没有更好的办法做到这一点?

ETO:

这里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转换提取为静态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());

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章