Sparky1 Sparky1 - 2 months ago 8
Java Question

Java: how to Iterate over a list of pojos and access their data?

In Java, how does one iterate over a list of pojos? I've found examples that show how to iterate over (and access the data in) a list of Strings or ints. But not a list of pojos

List<Policy> myPolicies = new ArrayList<Policy>();
myPolicies.add(new Policy(232 , "name" + my232, "desc" + my232));
myPolicies.add(new Policy(233 , "name" + my233, "desc" + my233));

// This does not work
for(int i = 0 ; i < policies.size(); i++ ) {
log.debug("policy: " + myPolicies[i].id);
}

public class Policy {
public int id;
public String name;
public String description;

public Policy(int id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
}

Answer

You are mixing up arrays and lists (collections).

The [] syntax only works for array types, such as

Object arrayOfObjects[] = { new Object() };
Object someObject = arrayOfObjects[0];

Whereas List is an interface, actually a subinterface of Collection; and those work like:

List<String> someStrings = new ArrayList<>();
someStrings.add("first");
String first = someStrings.get(0);

The easiest way to iterate lists and arrays is the for-each loop.

for (Policy policy : myPolicies) {
 ... there you go