开发者

How to get hold of current index when using Maps.uniqueIndex

开发者 https://www.devze.com 2023-02-10 12:45 出处:网络
We have a List of items: List<X> from this List, we would like to create Map<F(X), X> using Guava com.google.common.collect,

We have a List of items: List<X> from this List, we would like to create Map<F(X), X>

using Guava com.google.common.collect, there is Maps.uniqueIndex method, which takes a List as an input and allows us to apply a function to elements.

this is all great. for example:

List<File> to Map<String, File>

mapOfFileNames = Maps.uniqueIndex(fileList, new Function<File, String>() {
            @Override
            public String apply(@Nullable File input) {
                return input.getName();
            }
        });

my question is, how we can get hold of position of the current Item (index) in the List, when using Maps.uniqueIndex

for example, to convert List<File> to Map<Integer, File> I would like keys to be the position of File element in the List. therefore I need开发者_如何学编程 to get access to the index of the current element.

do you know how this can be possible ?

Thank You


Why do you want to do this? I don't really see the usefulness of it, given that you can do lookups in a List by index anyway. Getting the index of the input item in the Function would be wasteful because you'd have to do an indexOf for each item. If you really want to do this, I'd say just do:

List<File> list = ...
Map<Integer, File> map = Maps.newHashMap();
for (int i = 0; i < list.size(); i++) {
  map.put(i, list.get(i));
}

On a related note, all ImmutableCollections have an asList() view, which could allow you to do index-based lookup on any ImmutableMap. Maps.uniqueIndex also preserves the order from the original collection. Using your example:

ImmutableMap<String, File> mapOfFileNames = Maps.uniqueIndex(...);
/*
 * The entry containing the file that was at index 5 in the original list
 * and its filename.
 */
Map.Entry<String, File> entry = mapOfFileNames.entrySet().asList().get(5);
0

精彩评论

暂无评论...
验证码 换一张
取 消