如何将int [] []字符串转换为List< List< Integer>>. [英] How to convert int[][] string to List<List<Integer>>

查看:98
本文介绍了如何将int [] []字符串转换为List< List< Integer>>.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个类似"[[7], [2,2,3]]"的字符串.

There is a string like "[[7], [2,2,3]]".

如何将该字符串转换为List<List<Integer>>对象?

How can I convert this string to a List<List<Integer>> Object?

这是在JUnit5中实现参数转换器.

This is to implement a parameter converter in JUnit5.

@CsvSource({
    "'[2,3,6,7]', 7, '[[7], [2, 2, 3]]'"
})

我想将字符串"[[7], [2,2,3]]"转换为List<List<Integer>>对象.

I want to convert the string "[[7], [2,2,3]]" to a List<List<Integer>> Object.

推荐答案

尝试一下:

您在], [处拆分了输入字符串,这将为您提供以下各行:

you split your input string at ], [ which gives you following rows:

row[0]: [[7
row[1]: 2,2,3]]

然后消除'[[' ']]'字符串

row[0]: 7
row[1]: 2,2,3

然后,通过在','处进一步拆分行元素来对其进行迭代,并将每个元素添加到列表中.完成一行后,将其添加到listOfLists的列表中.

then you iterate over the elements of the rows by splitting them further at ',' and add each element to a list. When you are finished with one row you add it to the list of the listOfLists.

public List<List<Integer>> parseList(){
    String s  = "[[7], [2,2,3]]";

    return Arrays.stream(s.split("], \\["))
      .map(row -> row.replace("[[", "").replace("]]", ""))
      .map(row -> Arrays.stream(row.split(","))
        .map(Integer::parseInt).collect(Collectors.toList())
      ).collect(Collectors.toList());
}

这篇关于如何将int [] []字符串转换为List&lt; List&lt; Integer&gt;&gt;.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆