Java 8 forEach print with Index
A simple Java 8 tip to print the Array
or List
with index in the front.
1. Array with Index
Generate the index with IntStream.range
.
JavaListWithIndex.java
package com.mkyong.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", "Rust", "Go"};
List<String> collect = IntStream.range(0, names.length)
.mapToObj(index -> index + ":" + names[index])
.collect(Collectors.toList());
collect.forEach(System.out::println);
}
}
Output
0:Java
1:Node
2:JavaScript
3:Rust
4:Go
2. List with Index
Convert the List
into a Map
, and uses the Map.size
as the index.
Stream.java
<R> R collect(Supplier<R> supplier,
BiConsumer<R, ? super T> accumulator,
BiConsumer<R, R> combiner);
JavaListWithIndex.java
package com.mkyong.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", "Rust", "Go");
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));
}
}
Output
0:Java
1:Node
2:JavaScript
3:Rust
4:Go
its good but time consuming compare to imperative style of coding