简体   繁体   中英

Android Java remove item from list, filter list

I have a list of locations in my android application. I am trying to remove a location from a list , where location id equal to a certain value.

This is my location class:

public class Location{
     Private int locationId;
     Private String locationName;
}

So is there a way to remove a location from List<Location> without using a for or a while loop . Something like a lambda expression in C# :

var filteredLocations = locations.Where(x=>x.LocationId!=3).ToList();

There is a method in ArrayList to directly remove an object.

public boolean remove(Object o)

You will have to override the equals method for it to work. Internally, it's still gonna iterate over all the objects until it finds the required object.

Here is the link to the method.

As per this answer you can see that lambda expressions exist in Java 8 .

Code snippet from the answer:

final Array<Integer> a = array(1, 2, 3);  
final Array<Integer> b = a.map({int i => i + 42});  
arrayShow(intShow).println(b); // {43,44,45}  

Android does not suport all Java 8 features, however lambda expressions are suported, as you can see in the documentation .

You can add the list of array with out using any loop by using the below methods in the adapter

//you can use addItem all for adding data in array
    public void addItem(ClassName item) {
            mList.add(item);
            notifyItemInserted(mList.size() - 1);
        }

//delete all for deleting the whole list of data
        public void deleteAll() {
            mList.clear();
            notifyDataSetChanged();
        }

//For deleting a perticular item from data
        public void deleteItem(int index) {
            mList.remove(index);
            notifyItemRemoved(index);

        }

//For adding the whole set of array
        public void addAllItems(List<ClassName> items) {
            mList.addAll(items);
            notifyDataSetChanged();
        }

//For Updating a single item  
        public void updateItem(int index, ClassName item) {
            mList.set(index, item);
            notifyItemChanged(index);
        }

Where mList is the Array List

public List<ClassName> mList = new ArrayList<>();

You can try this.

ArrayList<Location> arrayList = new ArrayList<>(list.size());
arrayList.addAll(list);
arrayList.remove(index) OR arrayList.remove(object)

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