java - 通过将对象的属性/属性与字符串进行比较来检查对象列表是否已存在

标签 java android loops equals

我需要一些帮助,了解如何通过将每个对象字段或属性与给定的字符串值进行比较来检查我的对象列表是否会重复。

我的 POJO

public class AnnouncementModel extends AnnouncementsID {

  public String title, description, image, time;

  //Needed for Firebase
    public AnnouncementModel(){}

    public AnnouncementModel(String title, String description, String image, String time) {
        this.title = title;
        this.description = description;
        this.image = image;
        this.time = time;

    }
}

我想要的是将给定的字符串 id 与公告的 id 进行比较,如下所示

for(int i = 0; i < announcementList.size(); i++) {
    //Check if the deleted document ID is equal or exist in the list of announcement
    if(myGivenID.equals(announcementList.get(i).AnnouncementsID)) {

        //If yes then delete that object in list by targeting its index
        Log.d(TAG, "Removed city: " + announcementList.get(i).getTitle());
        announcementList.remove(i);
        //Notify the adapter that some item gets remove
        announcementRecyclerAdapter.notifyItemRemoved(i);
        announcementRecyclerAdapter.notifyItemRangeChanged(i,announcementList.size()-1);
     }
}

但我不想循环它,因为我只想检查它是否已经存在并且我也不需要它的索引。是否可以?我看到这可以使用 Java 8 Stream API 来完成,但就我而言,我无法使用它,因为它与 Android SDK 23 及更低版本不兼容。谁能给出完整的示例代码吗?

最佳答案

为了使 equals() 方法按预期工作,AnnouncementModel 类需要实现 hashcode()equals() 方法。

Eclipse 可以为您生成它们。否则任何基本的实现都可以工作。

关于java - 通过将对象的属性/属性与字符串进行比较来检查对象列表是否已存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50799489/

相关文章:

shell - 在嵌套的for循环中的shell脚本中运行shell脚本

具有奇怪值的 ruby​​ 数组

java - 计算指数增长系列中的值之和

java - ANDROID:创建一个需要按下 X 秒的按钮

android - 我如何以编程方式进行单铃调用以及如何判断我调用的线路是否已关闭?

javascript - 需要循环遍历并分别显示每个数组值 onClick - 没有 jQuery

java - 将值放入谷歌 Guava loadingCache中

Java 在循环内使用 jProgressBar

java - Hibernate 多对多协会?

android - E/flutter (8084): [ERROR:flutter/lib/ui/ui_dart_state. cc(157)]未处理的异常:SocketException:操作系统错误:连接被拒绝