Lele Lele - 1 year ago 50
Java Question

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

So I have an

that stores

I then have
which will store objects for each year

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
of each

For example

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

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.") {

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


Answer Source

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);

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download