-1

I have an Array of strings that I want to convert in a Map. Without using AtomicInteger or third party API.

sample:

final String[] strings = new String[]{"Arsenal", "Chelsea", "Liverpool"};

final Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < strings.length; i++) {
    map.put(i, strings[i]);
}

System.out.println(map);

which is the best and concise way to achieve so by using streams API?

Giuseppe Adaldo
  • 295
  • 3
  • 16

1 Answers1

0

After looking into it I found 2 possible solutions:

final Map<Integer, String> map = IntStream.rangeClosed(0, strings.length - 1)
        .mapToObj(i -> new SimpleEntry<>(i + 1, strings[i]))
        .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue));

And:

final Map<Integer, String> map = IntStream.rangeClosed(0, strings.length - 1)
        .boxed()
        .collect(toMap(i -> i + 1, i -> strings[i]));

Where I don't need to instantiate AbstractMap.SimpleEntry

Any better solution? Is there any advice on which one is the best way?

Giuseppe Adaldo
  • 295
  • 3
  • 16