Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove elements from ArrayList after finding element with specific char

Tags:

java

I have an ArrayList that contains a number of Strings, I want to be able to iterate through the ArrayLists contents searching for a string containing a semicolon. When the semicolon is found I then want to delete all of the Strings including and after the semicolon string.

So;

this, is, an, arra;ylist, string

Would become:

this, is, an

I feel like this is a very simple thing to do but for some reason (probably tiredness) I can't figure out how to do it.

Here's my code so far

public String[] removeComments(String[] lineComponents)
    {
        ArrayList<String> list = new ArrayList<String>(Arrays.asList(lineComponents));

        int index = 0;
        int listLength = list.size();
        for(String str : list)
        {
            if(str.contains(";"))
            {

            }
            index++;
        }
        return lineComponents;
    }

2 Answers

This becomes trivial with Java 9:

public String[] removeComments(String[] lineComponents) {
    return Arrays.stream(lineComponents)
                 .takeWhile(s -> !s.contains(";"))
                 .toArray(String[]::new);
}

We simply form a Stream<String> from your String[] lineComponents and take elements until we find a semicolon. It automatically excludes the element with the semicolon and everything after it. Finally, we collect it to a String[].

like image 167
Jacob G. Avatar answered Jul 06 '26 08:07

Jacob G.


First of all I think you are confusing arrays and arraylists. String[] is an array of strings while ArrayList<String> is an arraylist of strings. Take into account that those are not the same and you should read Array and ArrayList documentation if needed.

Then, to solve your problem following the ArrayList approach you can go as follows. Probably it's not the optimum way to do it but it will work.

public List<String> removeComments(List<String> lineComponents, CharSequence finding)
    {
        ArrayList<String> aux = new ArrayList<String>();

        for(String str : lineComponents)
        {
            if(str.contains(finding))
                break;
            else
                aux.add(str);
        }
        return aux;
    }
like image 32
Drubio Avatar answered Jul 06 '26 09:07

Drubio