[英]How would you convert A string into A Array/ArrayList
我有这段代码,我想在其中将字符串(例如 [15、52、94、20、92、109])转换为 Array/ArrayList。
我试过这段代码:
ArrayList<Byte> sdata = new ArrayList<>();
String bytessonvert = new String();
boolean run = true;
System.out.println("Enter Data: ");
String bytes = input.nextLine();
Bytes = bytes.substring(1, bytes.length());
for (int i = 0; i < bytes.length(); i++) {
if (Objects.equals(bytes.substring(i, i), " ")) {
sdata.add((byte) Integer.parseInt(bytessonvert));
bytessonvert = "";
} else if (bytes.substring(i, i) == ",") {
sdata.add((byte) Integer.parseInt(bytessonvert));
bytessonvert = "";
} else {
bytessonvert = bytessonvert + bytes.substring(i, i);
}
}
不需要字节。 Java 可以很好地处理文本。
使用String#split
制作零件数组。
制作该字符串部分数组的流。
使用Stream#map
将每个String
部分解析为一个Integer
对象,以生成新对象的另一个流。
将这些新的Integer
对象收集到一个不可修改的List
中。
List < Integer > integers =
Arrays
.stream(
"15, 52, 94, 20, 92, 109".split( ", " )
)
.map( Integer :: valueOf )
.toList() ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.