Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update all the elements of a list without loop

I have a list, Arraylist<User>. The User object has field active. I need to update all the user objects of the list with the active field as false.

Iterating through the list, I can update the field value. I want to know if there is any other way, using which I can update all the objects active field to 'false'?

like image 368
Yadu Krishnan Avatar asked Jun 12 '14 09:06

Yadu Krishnan


3 Answers

For java 8 you can use the stream API and lambdas

List<User> users;
users.forEach((u) -> u.setActive(false));
like image 135
Sergiy Medvynskyy Avatar answered Sep 22 '22 12:09

Sergiy Medvynskyy


If you're using Java 8, you can use the Iterable<E>.forEach(Consumer<? super E> action) method as follows:

users.forEach((user) -> user.setActive(false));

Otherwise you'll have to use the standard enhanced-for loop approach:

for (User user : users) {
    user.setActive(false);
}
like image 42
Edd Avatar answered Sep 23 '22 12:09

Edd


If you aren't using Java8, and can use 3rd party libraries, take a look at the Collection2.transform() function in the Google Guava library

Below is an example:

public class Main {

    public static void main(String[] args) throws Exception {

        List<Boolean> myList = new ArrayList<Boolean>();
        myList.add(true);
        myList.add(true);
        myList.add(true);
        myList.add(true);
        myList.add(true);

        System.out.println(Collections2.transform(myList, new Function<Boolean, Boolean>() {
            @Override
            public Boolean apply(Boolean input) {
                return Boolean.FALSE;
            }
        }));
    }//outputs [false, false, false, false, false]
}
like image 43
Gabriel Ruiu Avatar answered Sep 25 '22 12:09

Gabriel Ruiu