问题描述
有一个类似"[[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< List< Integer>>.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!