0

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);
    }
}
1
  • 1
    "a, b, c".split(",", -1) will result in an array like new String[] { "a", " b", " c"} - using split("\\h*,\\h*", -1) it will even eliminate eventual spaces before and after the , || -1 to avoid removing trailing empty strings Commented Jul 8, 2022 at 6:16

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

alternative: Pattern.compile(", ").splitAsStream("15, 20, 30").map(Integer::valueOf).toList() (not sure if it is easier to read [since it starts with a regular expression], probably only a matter of preference)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.