If you're sure that each object in the List
will have a unique index, use Guava with Jorn's suggestion of Maps.uniqueIndex
.
If, on the other hand, more than one object may have the same value for the index field (which, while not true for your specific example perhaps, is true in many use cases for this sort of thing), the more general way do this indexing is to use Multimaps.index(Iterable values, Function super V,K> keyFunction) to create an ImmutableListMultimap
that maps each key to one or more matching values.
Here's an example that uses a custom Function
that creates an index on a specific property of an object:
List foos = ...
ImmutableListMultimap index = Multimaps.index(foos,
new Function() {
public String apply(Foo input) {
return input.getBar();
}
});
// iterate over all Foos that have "baz" as their Bar property
for (Foo foo : index.get("baz")) { ... }