-1

How can I check if the array of IDs in my array list contain a particular string? I'm sure the question was probably answered elsewhere but I couldn't find anything (probably because I wasn't searching for the right questions).

Main Activity:

ArrayList<HomeJamaatItem> arrayJamaat = new ArrayList<>();

HomeJamaatItem:

public class HomeJamaatItem {

    private String ID;
    private String name;
    private String distance;
    private String fajrJamaat;
    private String zuhrJamaat;
    private String asrJamaat;
    private String maghribJamaat;
    private String eshaJamaat;

    public HomeJamaatItem(String ID, String name, String distance, String fajrJamaat, String zuhrJamaat, String asrJamaat, String maghribJamaat, String eshaJamaat) {
        this.ID = ID;
        this.name = name;
        this.distance = distance;
        this.fajrJamaat = fajrJamaat;
        this.zuhrJamaat = zuhrJamaat;
        this.asrJamaat = asrJamaat;
        this.maghribJamaat = maghribJamaat;
        this.eshaJamaat = eshaJamaat;
    }

    public String getID() {
        return ID;
    }

    public String getName() {
        return name;
    }

    public String getDistance() {
        return distance;
    }

    public String getFajr() {
        return fajrJamaat;
    }

    public String getZuhr() {
        return zuhrJamaat;
    }

    public String getAsr() {
        return asrJamaat;
    }

    public String getMaghrib() {
        return maghribJamaat;
    }

    public String getEsha() {
        return eshaJamaat;
    }
}

I've tried to use the .contains method but unfortunately, it didn't work:

if (!arrayJamaat.contains("Mcdougall")) {
   // Code
}
Raf A
  • 179
  • 1
  • 12
  • `contains()` will operate with the type that the `ArrayList` holds. If your list holds objects of type `HomeJamaatItem` and you pass a String to the method, it's not going to tell you if any of the fields of any object that your list holds has that value. But you can iterate through all the elements of the list and check one or more fields for the value you want to find. – JustAnotherDeveloper Sep 12 '20 at 16:33
  • I just search using your question title and get this linked question as first result. – Eklavya Sep 12 '20 at 17:40

2 Answers2

0

Loop on the list and check the string is present or not.

for(HomeJammat homejammat: arrayhomejammat) { 
    if(homejammat.getId().equals("comparestring")) {
        // code
    }
}
Vaibs
  • 1,546
  • 9
  • 31
  • This only works if you aren't modifying the array whilst you are iterating through it. Otherwise a great answer. – Raf A Sep 13 '20 at 10:26
0

You can use streams.

boolean matchExists = Arrays.stream(myArray).anyMatch(x -> "Mcdougall".equals(x.getID()));
Ali Ben Zarrouk
  • 1,891
  • 16
  • 24