Search code examples
javafor-looparraylistjsoup

Object is not being added to a list, list returns empty


I am retrieving data from a website and when I retrieve the data (String) then I get the display of countries

for (Element row : document.select("table.sortable.wikitable tr")) {

                if (row.select("td:nth-of-type(1)").text().equals("")) {
                    continue;

                }
else {
String name = row.select("td:nth-of-type(1)").text();
System.out.println(name);

}

this gives me the list of countries in my console, now that I have verified that I am getting the countries I want to insert each country into a separate country object using a list

final String url = "https://en.wikipedia.org/wiki/List_of_sovereign_states";
        List<Country> countries = new ArrayList<>();
        try {
            final Document document = Jsoup.connect(url).get();

            for (Element row : document.select("table.sortable.wikitable tr")) {

                if (row.select("td:nth-of-type(1)").text().equals("")) {
                    continue;

                } else {
                    for (Country country : countries) {

                        country.setCountry(row.select("td:nth-of-type(1)").text());


                        countries.add(country);

                    }

                }
            }
            System.out.println(countries);
        }

when I print the list the list is null

[]


Solution

  • The problem is here:

    else {
        for (Country country : countries) {
            country.setCountry(row.select("td:nth-of-type(1)").text());
            countries.add(country);
        }
    }
    

    Think about what the code is doing. When you hit your else block, you loop through your list of countries, and . . . create a new country as many times as there are existing countries in your list. But since the list starts as empty, that loop will never execute.

    The solution is simple. Get rid of the loop entirely, and just do this:

    else {
        Country country = new Country();
        country.setCountry(row.select("td:nth-of-type(1)").text());
        countries.add(country);
    }