使用Maps.uniqueIndex时如何获取当前索引

zix*_*gma 2 java guava

我们有一个项目列表:List<X> 从这个列表,我们想创建Map<F(X), X>

使用Guava com.google.common.collect,有一个Maps.uniqueIndex方法,它将List作为输入,并允许我们将一个函数应用于元素.

这一切都很棒.例如:

List<File> to Map<String, File>

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

我的问题是,我们如何能弄个位置当前项目用时列表中(指数)Maps.uniqueIndex

例如,转换List<File> to Map<Integer, File> 我希望键是List中File元素的位置.因此我需要访问当前元素的索引.

你知道这怎么可能吗?

谢谢

Col*_*inD 8

你为什么要这样做?鉴于你List无论如何都可以通过索引进行查找,我真的没有看到它的用处.获取输入项目的索引Function将是浪费,因为您必须indexOf为每个项目执行.如果你真的想这样做,我会说:

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

在相关的说明中,所有ImmutableCollections都有一个asList()视图,可以允许您对任何视图进行基于索引的查找ImmutableMap.Maps.uniqueIndex还保留原始集合中的订单.使用你的例子:

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);
Run Code Online (Sandbox Code Playgroud)