Java 8 forEach打印带有索引
下文笔者讲述java代码使用foreach打印出Array的索引信息呢?
使用IntStream.range生成索引
实现思路:
使用intstream.range生成指定范围的数据
使用mapToObj转换为键值对的模式
输出信息即可
例:使用IntStream.range生成索引
package com.java265.java8; import java.util.list; import java.util.stream.Collectors; import java.util.stream.IntStream; public class JavaArrayWithIndex { public static void main(String[] args) { String[] names = {"Java", "Node", "JavaScript", "C#", "Python"}; List<String> collect = IntStream.range(0, names.length) .mapToObj(index -> index + ":" + names[index]) .collect(Collectors.toList()); collect.forEach(System.out::println); } }
方式2:List转换为Map,使用Map.size作为索引
<R> R collect(Supplier<R> supplier,
BiConsumer<R, ? super T> accumulator,
BiConsumer<R, R> combiner);
package com.java265.java8;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class JavaListWithIndex {
public static void main(String[] args) {
List<String> list = Arrays.asList("Java", "Node", "JavaScript", "C#", "Python");
HashMap<Integer, String> collect = list
.stream()
.collect(HashMap<Integer, String>::new,
(map, streamValue) -> map.put(map.size(), streamValue),
(map, map2) -> {
});
collect.forEach((k, v) -> System.out.println(k + ":" + v));
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


