BACK-END/Java

How to get the foreach index in java.

02:00AM 2022. 1. 15. 14:25

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

--참고 레퍼런스

https://mkyong.com/java8/java-8-foreach-print-with-index/

 

Java 8 forEach print with Index - Mkyong.com

- Java 8 forEach print with Index

mkyong.com

 

'BACK-END > Java' 카테고리의 다른 글

replace what?!  (0) 2022.01.14
Qrcode & barcode 생성  (0) 2022.01.12