Reputation: 3
I have this code in which I want to convert a String (e.g. [15, 52, 94, 20, 92, 109]) to an Array/ArrayList.
I have tried this code:
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);
}
}
Upvotes: 0
Views: 62
Reputation: 340098
No need for bytes. Java handles text well.
Use String#split
to make an array of the parts.
Make a stream of that array of string parts.
Parse each String
part into a Integer
object using Stream#map
to make another stream of the new objects.
Collect these new Integer
objects into an unmodifiable List
.
List < Integer > integers =
Arrays
.stream(
"15, 52, 94, 20, 92, 109".split( ", " )
)
.map( Integer :: valueOf )
.toList() ;
See this code run live at Ideone.com.
Upvotes: 1