java8 遍历 int[] 变成 map
时间: 2023-07-22 08:30:48 浏览: 74
可以使用 Java 8 中的 Stream API 来遍历 int 数组并将其转换成 Map。以下是示例代码:
```java
int[] arr = {1, 2, 3, 4, 5};
// 将数组转换成 Map,键为数组元素,值为元素的平方
Map<Integer, Integer> map = Arrays.stream(arr)
.boxed()
.collect(Collectors.toMap(
Function.identity(),
x -> x * x
));
// 打印 Map
System.out.println(map);
```
以上代码使用了 `Arrays.stream()` 方法将 int 数组转换成 Stream,然后使用 `boxed()` 方法将 IntStream 转换成 Stream<Integer>。接着使用 `Collectors.toMap()` 方法将 Stream 转换成 Map,其中 `Function.identity()` 表示使用元素本身作为键,`x -> x * x` 表示将元素平方作为值。最终打印出转换后的 Map。
相关问题
java8 遍历 int[] 转为map 下标为键 值为值
可以使用 Java 8 中的 Stream API 来遍历 int 数组并将其转换成 Map,其中下标作为键,值作为值。以下是示例代码:
```java
int[] arr = {1, 2, 3, 4, 5};
// 将数组转换成 Map,键为数组下标,值为数组元素
Map<Integer, Integer> map = IntStream.range(0, arr.length)
.boxed()
.collect(Collectors.toMap(
Function.identity(),
i -> arr[i]
));
// 打印 Map
System.out.println(map);
```
以上代码使用了 `IntStream.range()` 方法生成一个包含数组下标的 IntStream,然后使用 `boxed()` 方法将 IntStream 转换成 Stream<Integer>。接着使用 `Collectors.toMap()` 方法将 Stream 转换成 Map,其中 `Function.identity()` 表示使用元素本身作为键,`i -> arr[i]` 表示将数组元素作为值。最终打印出转换后的 Map。
java for(int i )遍历map
在Java中,Map接口是一个存储键值对的数据结构,通常不直接支持用普通的`for(int i)`循环遍历,因为Map的元素是无序的,并且没有固定的索引。不过,你可以使用迭代器(Iterator)或者流(Stream)来遍历Map的内容。这里以两种方法为例:
1. 使用Iterator:
```java
Map<String, String> myMap = ...; // 假设这是你的Map
Iterator<Map.Entry<String, String>> iterator = myMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
int index = iterator.position(); // 如果你想用类似数组的索引,可以使用position()方法
String key = entry.getKey();
String value = entry.getValue();
// 进行其他操作,如打印或处理
}
```
2. 使用Stream(Java 8及以上版本):
```java
Map<String, String> myMap = ...;
myMap.entrySet().forEach((entry, index) -> { // 注意这里无法获取真正的索引,只能用entry的顺序
String key = entry.getKey();
String value = entry.getValue();
// 对每个键值对进行操作
});
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)