Java Guava 라이브러리에서 제공하는 Stream의 mapWithIndex 메소드

여기서는 guava의 라이브러리에 있는 mapWithIndex 메소드에 대해 설명한다.

Stream의 map에서 index를 제공

Java Stream에서 사용할 수 있는 map 함수는 index를 받아올 수 없다.

guava에서는 버전 21부터 Stream에서 index를 받아올 수 있는 mapmapWithIndex을 제공하고 있다.

여기서는 간단한 예제 코드를 제공하여 알아보도록 하자.

package com.devkuma.guava.stream;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.google.common.collect.Streams;

public class MapWithIndex {
    public static void main(String[] args) {
        List<String> results = Streams.mapWithIndex(
                Arrays.asList("a", "b", "c").stream(),
                (str, index) -> str + ":" + index
        ).collect(Collectors.toList());

        results.stream().forEach(r -> {
            System.out.println(r);
        });
    }
}

실행 결과:

a:0
b:1
c:2

첫번째 인자에는 Stream으로 만들려는 컬렉션(혹은 배열)이 지정하고, 두번째 인자에 람다 식을 지정한다.