0

There is a string[] arr = {"aa-bb-cc","dd-bb-ee","aa-hh-gg"} which needs to be split on the basis of , and -. The values aa,dd,aa should be stored in one list whereas bb,hh in another list. I have written this code snippet:

String[] arr = {"aa-bb-cc","dd-bb-ee","aa-hh-gg"};      
for(int i=0;i<arr.length;i++){          
    newArr =  arr[i].split(",");            
    for(int j=0;j<newArr.length;j++){               
    resultArr = newArr[j].split("-");                                                
    appList.add(resultArr[0]);               
    prodList.add(resultArr[1]);                 
    rolList.add(rresultArr[2]ol);        
}

Above approach could be better if we do arr[i].split in another way so that we can run only one loop but I could not achieve that so far.

I wanted to know is there any best way to achieve the requirement.

5
  • Splitting by , wont do much, since here it seperates the elements in the array... Commented Nov 5, 2015 at 7:14
  • @Harleen: considering that you are new on SO, whichever answer helped you solve your problem, you should mark it as correct. Commented Nov 5, 2015 at 7:28
  • Thanks a lot!!! @SarthakMittal . Commented Nov 6, 2015 at 11:47
  • What could be the best way to avoid ArrayIndexOutOfBoundException if say newArr[1] or newArr[2] is not available. I can very well handle in catch but I want the better way that there would be less chances to get such runtime exceptions. Commented Nov 6, 2015 at 11:48
  • @Harleen you can loop the array through its length, but then you will either have to use if-else or switch-case inside your loop, so it is better that you create an array of ArrayList which would contain appList, prodList and rolList and access them with the loop index... Commented Nov 6, 2015 at 12:53

1 Answer 1

3

You don't need to split it using , ,since it's not part of the String but part of the String array declaration syntax,just split it with a -

String[] arr = {"aa-bb-cc","dd-bb-ee","aa-hh-gg"};      
for(int i=0;i<arr.length;i++){          
newArr =  arr[i].split("-");                                                            
appList.add(newArr[0]);               
prodList.add(newArr[1]);                 
rolList.add(newArr[2]);        
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ya. This is the way to go

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.