Lele Lele - 13 days ago 5
Java Question

How to loop through List of objects of and compare value in every object in Java?

So I have an

object
that stores
Country
,
Year
and
Value


I then have
List<Object>
which will store objects for each year

Each
List<object>
consist of data of each range of years


I'd like to loop through any number of countries, let's say 4, and then in each object I want to retrieve the
value
of each
year
.

For example



Let's assume we want our object to return data from year
1980
to
1983


So my code looks like this:

//Example of our data
[AF, 19199437988.8023, 1980, AF, 20050189881.6659, 1981, AF, 20046334303.9661, 1982, AF, 20536542736.7297, 1983]
[UA, 90615023323.7353, 1980, UA, 131805126738.287, 1981, UA, 181334417615.413, 1982, UA, 175781379051.433, 1983]
[ID, 861933968740.332, 1980, ID, 890487074595.966, 1981, ID, 912524136718.019, 1982, ID, 917869913364.916, 1983]
[AU, 1339539063150.01, 1980, AU, 1454675479665.84, 1981, AU, 1563950959269.52, 1982, AU, 1537477830480.51, 1983]

// each value is a country. 'AF' stands for AFghanistan, and so on...
String[] countries = new String[] {
"AF", "UA", "ID", "AU"
};

for (int i = 0; i < countries.length; ++i) {
if (countries.get(i).getYear() == "I don't know how to retrieve each year here.") {
System.out.println(countries.get(i));
}
}




Is this possible? If so then how can I get it?

Thanks

Answer

Based on the answer: "This is just to illustrate my problem. I don't have such structure in my real application. The data above the code is just an example of how my data looks like"

I would suggest you to create a POJO that stores that data:

class POJO { //add nice name to class!
    private Map<Integer, Double> yearValueMap;
    private String countryName;
    // add setter and getter here.
    add(Integer year, Double value) {
        this.yearValueMap.put(year, value);
    }
}

And then you create objects that are storing that data, something like:

POJO pojo = new POJO();
pojo.add(1890, 14.31);
pojo.setCountryName("Italy");

and so you have objects containing this data. Then you have a

List<POJO> countryInformation;

that you can iterate.

Hope it helps and that I did not make any typo, I've coded it here.

Editing for adding the code in the comment:

List <Object> myData = receiveDataFromApi();
for(int i = 0; i < myData.size(); i+=3) {
    ...
    pojo.setCountryName= myData.get(i);
    pojo.add(myData.get(i+2), myData.get(i+1));
    ...
}

I've used the POJO just for making the point, but you should use your own model for that.