-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?

1
  • I don't think that question is related to this problem at all Commented Oct 17, 2019 at 9:11

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

3 Comments

.....mapToObj(i -> Map.entry(i + 1, strings[i])) in Java-9 above..though not necessarily required
Or without boxing overhead, IntStream.range(0, strings.length) .collect(HashMap::new, (m,i) -> m.put(i+1, strings[i]), Map::putAll)
Oh great, this is a more elegant solution

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.