简体   繁体   中英

Removing row in CSV file

I have created an ArrayList called entryList . The method I am trying to create is that if you write removeAllByDate() and enter a date, the entire line with that date should be removed. The entryList in turn consists of entries (rows) and I have also created the method getDate() . I thought of writing something like this:

public void removeAllByDate(String datum) {
    for(Entry entry: entryList) {
        if (entry.getDate().contains(datum)) {
            entryList.remove(entry);
        }
    }
}

Does anyone see why this does not work?

Since Java 8, the method to use when conditionally removing elements from a Collection is removeIf() . Your code will be as simple as the following:

entryList.removeIf(entry -> entry.getDate().contains(datum));

The original code is not working because removal of elements is not allowed while iterating over the collection, see this question and answers .

Nickewas, you're not being very forthcoming with Information:
- there are at least 2 different ArrayLists (eg java.util.ArrayList & java.util.Arrays.ArrayList)
- you don't mention how it doesn't work!

It may possibly be something to do with the following:
the for-each-loop uses an Iterator provided by your Iterable (entryList).
Maybe entryList.remove(entry) is having a side-effect on the Iterable?

Maybe this, or a variation thereof, would do it?

entryList.stream()
    .filter (entry -> entry.contains  (datum))  // Creates filtered Stream which...
    .forEach(entry -> entryList.remove(entry)); // ...maybe removes side-effect?

If not, you might have to use a Collector & iterate over the resulting List .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM