for list iterator and has to manipulate by index

Viewed 29

have a list of bean and I want to manipulate by its index and I tried below way, is there any other way of doing this which is easier and generic?

List<UserBean> resultBean = query.setFirstResult(offset).setMaxResults(limit).getResultList();          
    for (int i = 0; i < resultBean.size(); i++) {
       resultBean.get(i).setChabi(encode(decyptChabi(resultBean.get(i).getChabi())));
    }
1 Answers

As you can see from the Java Language Specification (JLS), 14.14, there are two kinds of for loops. The basic for loop, which uses an index, and the enhanced for loop, which doesn't.

You used the basic for loop but violated the DRY (Don't Repeat Yourself) principle in that you're calling resultBean.get(i) twice. To cure that, you can introduce a variable which makes the code much more readable:

    for (int i = 0; i < resultBean.size(); i++) {
        UserBean user = resultBean.get(i);
        user.setChabi(encode(decryptChabi(user.getChabi())));
    }

In your example, you don't even need the index variable, so you can replace the basic for loop with an enhanced for loop which would be even more concise:

    for (UserBean user : resultBean) {
        user.setChabi(encode(decryptChabi(user.getChabi())));
    }

Whatever you do, prefer code that is easy to read over code that is fast/easy to write.

Related