番石榴:将列表转换为以索引为键的地图 [英] guava: Transform a list to a map with the index as the key

查看:60
本文介绍了番石榴:将列表转换为以索引为键的地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我有一个列表名称。我希望将其转换为基于索引值的地图。例如

In my app I have a List names. I wish to convert this to a map based on the index value. For example

List<String> names = new ArrayList<String>();
names.add("Pratik");
names.add("Pratik");
names.add("Ram");
names.add("Varun");

您能帮我一些番石榴/ java api方法吗?即使有重复的值,索引和值也是名称吗?因此,如果名称中有两个 Pratik字符串。地图应该是这样的

Can you help me with some guava/java api method which can help me get a map where the key is the index and value is name even if there are duplicate values? SO if there are two "Pratik" String in names. The map should be like this


0-> Pratik,1-> Pratik,2-> Ram,3 -> Varun

0 -> "Pratik", 1->"Pratik",2->"Ram",3->"Varun"


推荐答案

我认为您在这里不需要番石榴:

I think that you don't need Guava here:

Map<Integer, String> map = new HashMap<Integer, String>();
int i = 0;
for (String name : names) {
    map.put(i++, name);
}

System.out.println(map);

打印:

{0=Pratik, 1=Pratik, 2=Ram, 3=Varun}

如果您绝对希望使用Guava做到这一点,可以这样做(但我建议使用JDK的方法来避免不必要的复杂性):

If you absolutely want a way to do it with Guava, you could do this (but I would recommend the JDK way to avoid unnecessary complexity):

Maps.asMap(
     ContiguousSet.create(Range.closedOpen(0, names.size()), DiscreteDomain.integers()),
          new Function<Integer, String>() {
              @Override
              public String apply(Integer input) {
                  return names.get(input);
              }
          });

顺便说一句,我不明白你为什么要这么做。

By the way, I don't see why you would have to do this.

这篇关于番石榴:将列表转换为以索引为键的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆