Actualizar todos los elementos de una lista sin bucle

Tengo una lista 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'?

preguntado el 12 de junio de 14 a las 10:06

¿Qué versión de Java estás usando? -

Basic thing, without iterating how can you access and update it's contents ? -

I dont have the object to set it into the list, I only want to update a field of the User Object -

4 Respuestas

For java 8 you can use the stream API and lambdas

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

Respondido el 12 de junio de 14 a las 10:06

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. - Yadu Krishnan

@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. - Edd

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. - Yadu Krishnan

If you're using Java 8, you can use the Iterable<E>.forEach(Consumer<? super E> action) método de la siguiente manera:

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

Respondido el 12 de junio de 14 a las 10:06

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

A continuación se muestra un ejemplo:

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]
}

Respondido el 12 de junio de 14 a las 10:06

This sounds like a job for functional programming and Java 8. You could do something like this:

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

If you don't use Java 8, there are similar libraries such as LambdaJ

Respondido el 12 de junio de 14 a las 11:06

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.