Skip to content
Advertisement

Remove Alternate Elements from ArrayList in java 7

I have an array of String containing below elements

5.0,99,5.5,100,6.0,101

Now what I want to do I need to remove all the decimal value in string format like 5.0,5.5 and 6.0

so my final array should contain elements 99,100,101

so what I’d done so far is show in below code

public static String[] deleteElement(String[] str_array) {
        //String[] str_array = {"item1","item2","item3"};
        List<String> list = new ArrayList<String>(Arrays.asList(str_array));
        
        list.remove("5.0");
        list.remove("5.5");
        list.remove("6.0");
        return str_array = list.toArray(new String[0]);
    }

I have hardcoded the values which is quite bad practice as the values in future may be more than the current values, so I want a way to remove by using index.

I have tried to remove using remove(index) also, using even index positioning like 0,2,4,but what actually happening is, after deletion of 5.0 , elements are shifted left side, so 100 comes into the 2nd position, and in next iteration 100 deleted.

So is there any way where I can construct a generic function so if there are more elements in decimal value so it can also be deleted.

NOTE: The string decimal values will always be residing on even index positioning.

Advertisement

Answer

We have traversed the List from list.size() -1 to 0
So that number arent pushed in front.
when you traverse it from 0 to size of the list and then if you delete an element 1 element is skipped cause size() of the list decreases and i keeps incrementing.
eg.[“5.0″,”6.1″,”5.5″,”100″,”6.0″,”6.6”] when you traverse form 0 to size() - 1
i = 0 :
5.0 is seen and removed and then the list is like ["6.1","5.5","100","6.0","6.6"] where now 6.1 is at 0 index.

i = 1:
5.5 is removed and then the list is like
["6.1","100","6.0","6.6"] where now 100 is at 1 index.

and so on.

But when traverse from size-1 to 0 it will remove every single element without the fear of missing any decimal number.
Try this on your own and you will get to know why it is working and why 0 to n-1 isn’t working.

            String arr[] = {"5.0","99","5.5","100","6.0","101"};
            List<String> list = new ArrayList<String>(Arrays.asList(arr));
            for(int i = list.size() - 1 ; i >= 0 ; i--) {
                String number = list.get(i);
                if(number.contains(".")) {
                    list.remove(number);
                }
            }
            
            for(String val : list) {
                System.out.println(val);
            }

output:

99
100
101
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement