1

我有 2 个字符串数组。如何一次遍历两个数组以创建一个 HashMap,其中 Key 来自第一个数组,值来自第二个数组。

例如。Array1 = {“A”、“B”、“C”、“D”}
Array2 = {“苹果”、“男孩”、“猫”、“狗”}

结果 HashMap = [{A:apple}, {B:boy}, {C:cat}, {D:dog}]

这是我的代码,但它不起作用。

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

1 回答 1

2

假设它们具有相同的大小,则没有重复项或空值:

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

你也可以用java SimpleEntry- Arrays.asList9替换List.of

或者:

IntStream.range(0, first.length)
         .boxed()
         .collect(Collectors.toMap(x -> first[x], y -> second[y]))
于 2018-05-02T08:18:54.823 回答