Java Guavaライブラリが提供するStreamのmapWithIndexメソッド

ここでは、GuavaライブラリにあるmapWithIndexメソッドについて説明する。

Streamのmapでindexを提供する

Java Streamで使用できるmap関数は、indexを受け取ることができない。

guavaではバージョン21から、Streamでindexを受け取れるmapであるmapWithIndexを提供している。

ここでは簡単なサンプルコードで確認してみよう。

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

第1引数にはStreamにするコレクションまたは配列を指定し、第2引数にはラムダ式を指定する。