Vinoth Vinoth - 5 months ago 9
Java Question

How to convert string array

I have a string array that holds the value in this fashion .
[vi , 26 , new york , retired] [ji, 27 , manhattan , retired] [ti, 28 , manhattan , working] and so on

I converted string array to Array list and i gave

arr.get(1)
which is giving me the value
26
,
27
,
28
so on.

I want to iterate the fields in a fashion it should take vi , 26 , new york , retired in the 1st iteration , ji, 27 , manhattan , retired in the 2nd iteration and so on. So i can get the value based on index for each iteration . lets say arr.get(0) gives me vi , get(1) gives me 27 n so on

where count is the number of lines in the file which is 3 in this example and the file was initially pipe separated

for (int i = 0; i < count; i++) {
int len = arr.get(i).length();
String[] s = arr.get(i).toString().split("\\|");
List<String> wordList = Arrays.asList(s);
System.out.println(wordList.get(1));


when i gave wordList.get(1) . i m getting the output 26,27,28

Answer

The issue is that you are iterating through each string array and updating the s variable each time. Then you are outputting that specific index of the original arr (is this an ArrayList?). I recommend you create a variable that holds Lists objects outside the loop:

     List<List<String>> container;

     for (int i = 0; i < count; i++) 
      {
        int  len = arr.get(i).length();
        String[] s = arr.get(i).toString().split("\\|");
        List<String> wordList = Arrays.asList(s);
        container.add(wordList);
       }

Then you can get each object from this List of Lists object:

container.get(0).get(1) //would return only 26.

This is assuming there isn't something else wrong with your code. I feel like not all of the code is presented though. The methodology would be the same regardless.

Comments