Update all the elements of a list without loop

12,455

Solution 1

For java 8 you can use the stream API and lambdas

List<User> users;
users.forEach((u) -> u.setActive(false));

Solution 2

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);
}

Solution 3

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]
}
Share:
12,455
Yadu Krishnan
Author by

Yadu Krishnan

I am a Java and Scala enthusiast. Interested in learning new things.

Updated on June 07, 2022

Comments

  • Yadu Krishnan
    Yadu Krishnan almost 2 years

    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'?

  • Yadu Krishnan
    Yadu Krishnan almost 10 years
    Thanks for the answer. I think, I will g with this. This is also a form of for loop, but this reduces the no. of lines.
  • Edd
    Edd almost 10 years
    @YaduKrishnan I wouldn't worry about reducing the number of lines, I'd be more concerned about making the code as easy to understand as possible. In this case I think the lambda syntax achieves that, but my point is that, in general, using more lines to express something is not necessarily a bad thing.
  • Yadu Krishnan
    Yadu Krishnan almost 10 years
    Yes, but in my case, i have to do this in more than one list. Currently, i have to do the similar code in 4 lists. In this case, the number of lines increases drastically.