Small things: For Each in different languages

In web programming, a lot of times you will have to handle lists or other types of collections, passing through the collection and doing whatever you want to do with the collection’s elements. There are some ways to do that, so I will tell one way I use a lot and it’s very simple to use, besides being an elegant way of programming.

I use the forEach iteration.

Let’s see an example in Java:

Supposing we have a very simple class called Person.java

public class Person {

    private String name;

    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

And we will iterate over a list of Persons (personList):

// supposing we have a list of Persons (List<Person>)
if(personList != null) {
    for(Person person : personList) {
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());
    }
}

It’s always a good practice checking if the list is not null, to avoid java.lang.NullPointerException.

Let’s see an example in jsp:

In jsp, let’s suppose that we will receive a list of Persons, just like the above example. The list is called personList (List<Person>).

In jsp, to iterate over a list loop we can use a core tag lib called forEach.

<c:forEach var="person" items="${personList}">
    <c:out value="${person.name}"/><br/>
    <c:out value="${person.age}"/><br/>
<c:forEach>

In the above code we show all Persons. We use the core tag lib out to print the data from each object in the list. The personList and its’ objects ate caught via JSP Expression Language.

Let’s see some examples in Javascript:

In javascript we can iterate over an array, using a Javascript’s own commands. This link is a StackOverflow question/answer which covers that.

Another way to do this is using jQuery, which has a command to iterate over arrays. See this link to learn more about jQuery .each().

That’s all folks!

I hope I helped somebody using forEach way to iterate over lists/collections. Any doubt, I’m ready to solve your problem! Thanks!