Pratik Shelar
Pratik Shelar

Reputation: 3214

guava: Transform a list to a map with the index as the key

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");

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"

Upvotes: 3

Views: 6103

Answers (1)

LaurentG
LaurentG

Reputation: 11717

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);

prints:

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

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.

Upvotes: 8

Related Questions