Returns a map with the given {@code values}, indexed by keys derived from those values. In other words, each input value produces an entry in the map whose key is the result of applying {@code keyFunction} to that value. These entries appear in the same order as the input values. Example usage: {@s
(
Iterable<V> values, Function<? super V, K> keyFunction)
| 1322 | * keyFunction} produces {@code null} for any value |
| 1323 | */ |
| 1324 | @CanIgnoreReturnValue |
| 1325 | public static <K, V> ImmutableMap<K, V> uniqueIndex( |
| 1326 | Iterable<V> values, Function<? super V, K> keyFunction) { |
| 1327 | class="cm">// We can provide a hint to the builder to preallocate the correct size when the iterable is |
| 1328 | class="cm">// either a List (which likely has a fast size() implementation), or an ImmutableCollection |
| 1329 | class="cm">// (which definitely has a fast size() implementation). While Collection also has a size() |
| 1330 | class="cm">// implementation, it _may_ require iteration over the entire collection (e.g., a |
| 1331 | class="cm">// FilteredCollection), which we want to avoid. |
| 1332 | if (values instanceof List || values instanceof ImmutableCollection) { |
| 1333 | return uniqueIndex( |
| 1334 | values.iterator(), |
| 1335 | keyFunction, |
| 1336 | ImmutableMap.builderWithExpectedSize(((Collection<?>) values).size())); |
| 1337 | } |
| 1338 | return uniqueIndex(values.iterator(), keyFunction); |
| 1339 | } |
| 1340 | |
| 1341 | /** |
| 1342 | * Returns a map with the given {@code values}, indexed by keys derived from those values. In |