Search code examples
javaarraysarrayliststringtokenizer

Java How to split arralyist and set in a separate string or array


I am new in Java. I have an object which contains below data

1002,USD,03/09/2019,1004,2,cref,,,,,,,,,
1002,USD,03/09/2019,1005,3,cref,,,,,,,,,
1002,USD,03/09/2019,1003,3,cref,,,,,,,,,

I used StringTokenizer to conver this in arraylist

List<String> elements = new ArrayList<String>();
StringTokenizer st = new StringTokenizer((String) object);

while(st.hasMoreTokens()) {
    elements.add(st.nextToken());
}

Tokenizer convert this in below form

[1002,USD,03/09/2019,1004,2,cref,,,,,,,,,, 
 1002,USD,03/09/2019,1005,3,cref,,,,,,,,,, 
 1002,USD,03/09/2019,1003,3,cref,,,,,,,,,]

I want the third index of each line (1004,1005,1003) in a separate string or a separate array. Please advise or is there any other way to get the third index without using tokenizer.

java version "1.8.0_161" Java(TM) SE Runtime Environment (build 1.8.0_161-b12) Java HotSpot(TM) 64-Bit Server VM (build 25.161-b12, mixed mode)


Solution

  • To get the needed value (4th item) from each row, you can use String.split() function:

    List<String> elements = new ArrayList<String>();
    StringTokenizer st = new StringTokenizer((String) object);
    
    while(st.hasMoreTokens()) {
        String[] row = st.nextToken().split(",");
        if (row.length > 3) {
            elements.add(row[3]);
        }
    }