0

I have a class CountryModel with two columns in it Name and Code and my problem is that I don't know how to search in this prognathically.

Say I want to search where country name is "Aruba" given the fact I got methods like getName()

ArrayList<CountryModel> countries = new ArrayList<>();
countries.add(new CountryModel("Afghanistan", "93"));
countries.add(new CountryModel("Australia", "61"));
countries.add(new CountryModel("Aruba", "297"));

Of course I know how to search a single column using the contains() function but this one has become uphill task for me.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97

4 Answers4

1

You could just use a stream here:

List<CountryModel> countries = new ArrayList<>();
// populate list

List<CountryModel> matches = countries.stream()
            .filter(c -> "Afghanistan".equals(c.getName())
            .collect(Collectors.toList());

Ideally, we'd like to overload the equals() method of CountryModel, but for your search case, you aren't looking for an entire object, just a property of some object. So, iterating the list in some way might be the only option here.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

A simple loop with an if statement in it will easily solve your issue

public static void main(String... args){
       ArrayList<CountryModel> countries = new ArrayList<>();
       countries.add(new CountryModel("Afghanistan", "93"));
       countries.add(new CountryModel("Australia", "61"));
       countries.add(new CountryModel("Aruba", "297"));

       searchLoop(countries, "Aruba", "297");
   }

    private static Optional<CountryModel> searchLoop(ArrayList<CountryModel> countries, String name, String code) {
        for(CountryModel model : countries){
            if(model.getName().equals(name) && model.getCode().equals(code)){
                return Optional.of(model);
            }
        }
        return Optional.empty();
    }

Can be updated to stream also but not really usefull in there without more context

Wisthler
  • 577
  • 3
  • 13
0

Before Streaming API (just in case you can not use streams(java8))

for (CountryModel l1 : l) {
    if ("Aruba".equalsIgnoreCase(l1.getName())) {
        System.out.println("Found!!");
        break;
    }
}

since java 8: in your case, collecting to a list is not pretty oprimal, since is hard to believe, you can have more than one country with the same name, therefore,

CountryModel matches = l.stream()
     .filter(c -> "Aruba".equalsIgnoreCase(c.getName()))
     .findAny()
     .orElse(null);      
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

This should help you as it does not use stream API that others have suggested since you could be targeting lower APIs like 16 for instance

for (int i = 0; i < countries.size(); I++) {
    if (countries.get(i).getTitle().equals ("Afghanistan")) {
    }
}