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'?
For java 8 you can use the stream API and lambdas
List<User> users;
users.forEach((u) -> u.setActive(false));
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);
}
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]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With