I have an ArrayList of objects. The objects are all of the same class and contain a public field that is a boolean data type. Is it possible to determine if any instances within the arraylist exist where this field is set to true without having to iterate through the entire array and checking each field? Just wondering whether there is a shorthand version of an iteration loop. Thank you.
4 Answers
No.
Unless you have some additional structure that keeps track of the values in the list in some way (for example by tracking each addition/removal and making sure that the boolean field can't change after addition) there is no way to check for this without iteration.
Iteration can be "hidden" via recursion or inside another method, but that doesn't change anything in a significant way.

- 302,674
- 57
- 556
- 614
There is no support for this in the JDK because without proper closures the syntax is terribly convoluted. There is a library out there that achieves a balance between terse syntax and usability: LambdaJ. The hacks involved to achieve this are an amazing story on their own.

- 195,646
- 29
- 319
- 436
There is no such thing in Java.
However, Guava offers this kind of thing using a Predicate and Collections2.filter(). But it's not a one-line thing.

- 47,259
- 4
- 83
- 117
Kind of...
You're looking for something like LINQ for Java, so you can do something similar to
collection.any(x => x.bool)
Here are some libraries:
What is the Java equivalent for LINQ?
If you look through them you should find some short hand functions to do that, but all of them iterate through the collection somehow (just hidden beneath a function).

- 1
- 1

- 4,994
- 1
- 27
- 41
-
Yes, something similar to LINQ, only I was hoping it was already built into the Java language. – Johann May 22 '12 at 13:06