Say I have an list of objects with two fields field1
and field2
, both of String type.
How do I get a list of all field1
values wit
... whether your questions refers to avoiding iterating over the collection
either:
Concretely, do you mean:
See below for solutions and options.
If it's the first one, then look at Google Guava, LambdaJ, FunctionalJava or other libraries that implement basic functional constructs and will allow you to do what you want in a few expressive calls. But keep in mind these do what is says on the tin: they will filter, collect or transform a collection, and will iterate through its elements to do this.
For instance:
Google Guava:
Set strings = buildSetStrings();
Collection filteredStrings =
Collections2.filter(strings, Predicates.containsPattern("^J"));
Functional Java:
Array a = array(97, 44, 67, 3, 22, 90, 1, 77, 98, 1078, 6, 64, 6, 79, 42);
Array b = a.filter(even);
LambdaJ:
List biggerThan3 = filter(greaterThan(3), asList(1, 2, 3, 4, 5));
If it's the second one, this is not possible as-is, except if you architectured everything from the start so that your objects should be managed by a custom collection class that would indexing your objects based on their field values on insertion.
It would keep them in buckets indexed by said value to be readily available for you to retrieve them as a list or set on demand.
As mentioned in the comments below dounyy's answer, designing such a custom collection would probably have an impact on the API of the elements it would accept (most likely by defining a super interface to use for element types), or would require a fairly intricate implementation to resolve members dynamically (most likely by using reflection), if you ever wanted this collection to be generic.