Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in checking ArrayList elements (extracted from a csv file) in Java and parsing them using the required logic

I read a CSV file,which looks as shown below.

,Tmt 1,Tmt 2,Tmt 3
delta 1,-104,-100,-103
delta 2,-125,-103,-103
delta 3,-104,-100,failed

Later, I parsed the csv file and took in all of its elements to an ArrayList of Strings. Now the ArrayList looks like

[Tmt 1, Tmt 2, Tmt 3, delta 1, -104, -100, -103, delta 2, -125, -103, -103, delta 3, -104, -100, failed]

Now, I want to remove all the elements of the String ArrayList (shown above) which starts with an alphabet. I used the following code to do that. (al1 is the ArrayList I mentioned above and temp is the String I'm using to check the elements of al1)

for(int i=0;i<al1.size();i++)
  {   
    temp = al1.get(i);  
    if (temp.charAt(0)=='-'|| (Character.isDigit(temp.charAt(0))==false))
           {
               al1.remove(i);    
           }    
  }
System.out.print(al1); 

Now after the code runs and hoping to remove elements of al1 starting with an alphabet , I printed the ArrayList al1, and the result was as follows:

[Tmt 2, delts 1, -100, delta 2, -103, delta 3, -100]

(and this was not what I expected)

Please Help.. thanks in advance

like image 986
HARSHA VARDHANA Avatar asked Aug 15 '26 13:08

HARSHA VARDHANA


2 Answers

The problem is you are using index to remove the element.

When you remove one element, your i will be off, after first removal you will not be removing the correct element.

Say your i is 5 and you have removed that element, in the next iteration when i is 6, when you do al1.get(i) you will actually get 7th element in the original list, not 6th because your 6th element index now is 5 but not 6. So you will not be able to access that element at all.

your for(int i=0;i<al1.size();i++) is also incorrect, because you are incrementing i and reducing the size of al1.

In worst case(when all the elements in the list starts with '-'), you will be able to traverse only half of the elements.

Safer way to do is using an Iterator.

Iterator<> it = al1.iterator();
while(it.hasNext()){
     temp = it.next();  
     if (temp.charAt(0)=='-'|| (Character.isDigit(temp.charAt(0))==false))
       {
           it.remove();    
       }  
}
like image 176
Karthik Avatar answered Aug 18 '26 02:08

Karthik


you can use built-in removeif method as:

al1.removeIf(new Predicate<String>() {

            @Override
            public boolean test(String t) {
                 if (t.charAt(0)=='-'|| (Character.isDigit(t.charAt(0))==false)){
                       return true;
                }
                return false;
            }
        });
like image 31
Rustam Avatar answered Aug 18 '26 02:08

Rustam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!