简体   繁体   English

将多行字符串强制转换为列表 <String> 在Java中

[英]Coerce multiline string to List<String> in Java

One of the outputs of some Model class in my application comes as a multiline string of the following format: 我的应用程序中某些Model类的输出之一是以下格式的多行字符串:

System.out.println(str); //output:

row1
row2
row3
row4

There might be many values/lines in a string depending on the output, so str string is just for example purposes. 根据输出的不同,字符串中可能有很多值/行,因此str字符串仅用于示例目的。 I would like this string to be coerced into List<String> if possible, so the printed output will be shown as: 如果可能,我希望将此字符串强制转换为List<String> ,因此打印的输出将显示为:

List<String> listStr = new ArrayList<String>();
System.out.println(listStr); //output:

[row1, row2, row3, row4]

I tried many different approaches eg: 我尝试了许多不同的方法,例如:

for (Model modelRow : modelTableView.getItems()) {
            str = modelRow.getInfo();
            System.out.println(str);
            listStr = new ArrayList<String>(Arrays.asList(str.split("\n")));
}

In most cases only the last value is returned or I get single arrays for all values eg: 在大多数情况下,仅返回最后一个值,否则我将获得所有值的单个数组,例如:

[row1]
[row2]
[row3]
[row4]

So, how can I have all values in one List only [row1, row2, row3, row4] ? 因此,如何将所有值都仅包含在一个列表中[row1, row2, row3, row4] What am I missing? 我想念什么? Any help or directions would be appreciated. 任何帮助或指示,将不胜感激。

EDIT 编辑

I avoided using a separator with a str.split() method and I queried the cells in the firstColumn within the modelTableView directly using the following: 我避免使用带有str.split()方法的分隔符, modelTableView直接使用以下firstColumnmodelTableViewfirstColumn查询单元格:

for (int i=0; i < modelTableView.getItems().size(); i++) {
            str = firstColumn.getCellData(i);
            System.out.println(str);
            listStr = Arrays.asList(str);
}

The code doesn't return NullPointerException anymore and allows to continue, however the output of listStr is just the last element of the original str string: 该代码不再返回NullPointerException并允许其继续,但是listStr的输出只是原始str字符串的最后一个元素:

System.out.println(listStr);
//output:
[row4]

Should I change an iterator within the loop? 是否应该在循环中更改迭代器? Any other idea what could go wrong? 还有其他想法可能出什么问题吗?

Try something like this: 尝试这样的事情:

List<String> listStr = new ArrayList();
for (Model modelRow : modelTableView.getItems()) {
   str = modelRow.getInfo();
   System.out.println(str);
   listStr.addAll(Arrays.asList(str.split("\n")));
}

EDIT 编辑

If you just want to print an array in the way a List is printed, you could use: 如果只想以打印List的方式打印数组,则可以使用:

Arrays.toString( array )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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