数组转换为map key
时间: 2023-08-01 17:12:00 浏览: 60
可以使用 Java 中的 HashMap 类来实现将数组转换为 Map,其中数组的元素作为 Map 的 key,可以给每个元素赋一个默认的 value 值,如下所示:
```java
import java.util.HashMap;
import java.util.Map;
public class ArrayToMapExample {
public static void main(String[] args) {
String[] array = {"key1", "key2", "key3"};
Map<String, Integer> map = new HashMap<>();
for (String key : array) {
map.put(key, 0); // 默认 value 为 0
}
System.out.println(map);
}
}
```
输出结果为:
```
{key1=0, key2=0, key3=0}
```
这样就将数组转换成了一个 Map,其中数组元素作为 key,value 为默认值 0。
相关问题
使用lodash方法将包含{samPrefix,samLabels}对象的数组转换成map,key为samPrefix,value为samLabels
可以使用`_.reduce()`方法来将包含{samPrefix,samLabels}对象的数组转换成map。
以下是示例代码:
```javascript
const data = [
{samPrefix: 'a', samLabels: ['label1', 'label2']},
{samPrefix: 'b', samLabels: ['label3', 'label4']},
{samPrefix: 'c', samLabels: ['label5', 'label6']}
];
const result = _.reduce(data, (acc, {samPrefix, samLabels}) => {
acc[samPrefix] = samLabels;
return acc;
}, {});
console.log(result);
// Output: {a: Array(2), b: Array(2), c: Array(2)}
```
在这个例子中,我们使用 `_.reduce()` 方法来遍历数组 `data`,对于每个元素,我们将其 `samPrefix` 属性作为键,`samLabels` 属性作为值,添加到最终的对象中。初始值为一个空对象 `{}`。
输出的结果为一个对象,其中键名为 `samPrefix`,键值为对应的 `samLabels` 数组。
es6 数组如何转为 map
可以使用数组的 `reduce` 方法将数组转换为 map。例如,假设有一个数组 `arr`,其中每个元素都是一个对象,每个对象都有一个 `id` 属性和一个 `value` 属性,我们可以将其转换为一个以 `id` 为 key,`value` 为 value 的 map,代码示例如下:
```
const arr = [
{ id: 1, value: 'foo' },
{ id: 2, value: 'bar' },
{ id: 3, value: 'baz' },
];
const map = arr.reduce((acc, cur) => {
acc.set(cur.id, cur.value);
return acc;
}, new Map());
console.log(map); // Map { 1 => 'foo', 2 => 'bar', 3 => 'baz' }
```
在上面的代码中,`reduce` 方法的第一个参数是一个回调函数,它接受两个参数 `acc` 和 `cur`,分别代表累加器和当前元素。回调函数将当前元素的 `id` 作为 key,`value` 作为 value 存入累加器 `acc`(一个新创建的 Map 对象),并最终返回累加器 `acc`。最终得到的 `map` 就是转换后的结果。