简体   繁体   中英

How would you convert A string into A Array/ArrayList

I have this code in which I want to convert a String (eg [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);
    }
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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