1

I have two arrays of Strings. How can I loop through both arrays at once to create a HashMap<String, String> where the key is coming from first array and the value is coming from the second array?

eg.

Array1 = {"A", "B", "C", "D"}
Array2 = {"apple", "boy", "cat", "dog"}

Resulting HashMap:

[{A:apple}, {B:boy}, {C:cat}, {D:dog}]

Here is my code, but it's not working.

AtomicInteger index = new AtomicInteger();
Stream<String> stream = Stream.of(array2);
stream.forEach(x -> mappedData.put(array1[index.getAndIncrement()],x));
1

1 Answer 1

3

Assuming they have the same size, there are no duplicates or nulls:

IntStream.range(0, first.length)
         .mapToObj(x -> new SimpleEntry<>(first[x], second[x]))
         .collect(Collectors.toMap(Entry::getKey, Entry::getValue))

you can replace SimpleEntry with Arrays.asList or in java-9 List.of also

Or:

IntStream.range(0, first.length)
         .boxed()
         .collect(Collectors.toMap(x -> first[x], y -> second[y]))
Sign up to request clarification or add additional context in comments.

3 Comments

Or Java 9’s Map.entry(…, …).
instead of assuming they are equal length you could also use IntStream.range(0, Math.min(first.length, second.length))
@Lino I thought about that... but was not sure what the OP would think about it as his example has them to be same length. Still, thx for he addition

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.