Sparky1 Sparky1 - 1 year ago 104
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) { = id; = name;
this.description = description;

Answer Source

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<>();
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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download