【问题标题】:Android Java remove item from list, filter listAndroid Java从列表中删除项目,过滤器列表
【发布时间】:2016-11-17 18:57:01
【问题描述】:

我的android 应用程序中有一个位置列表。我正在尝试从list 中删除一个位置,其中位置 ID 等于某个值。

这是我的位置类:

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

那么有没有一种方法可以在不使用for 或while loop 的情况下从List<Location> 中删除位置。类似于C# 中的lambda 表达式:

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

【问题讨论】:

  • 在您的适配器中,您可以使用以下函数 mList.remove(index); 创建一个方法; notifyItemRemoved(index);
  • 你被绑定到一个列表吗?在这种情况下 Map 会更好
  • 由于 Android 不支持 Java 8,因此您无法访问大多数面向 lambda 的 API。第三方库 retrolambda 提供了对 lambdas 的有限支持。在您的情况下,您可以切换到 Map 或 SparseArray 或使用旧的 for。

标签: java android list


【解决方案1】:

您可以使用适配器中的以下方法添加数组列表而无需使用任何循环

//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);
        }

其中 mList 是数组列表

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

【讨论】:

    【解决方案2】:

    ArrayList 中有一个方法可以直接删除对象。

    public boolean remove(Object o)
    

    您必须重写 equals 方法才能使其工作。在内部,它仍然会遍历所有对象,直到找到所需的对象。

    这是该方法的link。

    【讨论】:

      【解决方案3】:

      根据this的回答,您可以看到lambda表达式存在于Java 8中。

      答案中的代码 sn-p:

      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 不支持所有Java 8 功能,但支持lambda 表达式,如您在documentation 中所见。

      【讨论】:

        【解决方案4】:

        你可以试试这个。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-08-31
          • 2013-04-22
          • 1970-01-01
          • 1970-01-01
          • 2022-12-20
          • 2014-07-30
          • 1970-01-01
          • 2015-04-02
          相关资源
          最近更新 更多