LoginSignup
1
1

More than 3 years have passed since last update.

【Java】Stream API/map

Posted at

オブジェクト内の全ての要素を変換するメソッド

public class Fruit {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();
        list.add("apple");
        list.add("orange");
        list.add("banana");

        List<String> ret = list.stream().map(s -> s.toUpperCase()).collect(Collectors.toList());
        ret.forEach(System.out::println);
    }
}

//出力結果は要素が大文字になる

(.collect(Collectors.toList());はListで返すためにつけてる)

ラムダ式を使わなければ以下のようになる。

        List<String> ret = list.stream().map(new Function<String,String>(){
            @Override
            public String apply(String s) {
                System.out.println(s);
                return s.toUpperCase();
            }
        }).collect(Collectors.toList());

map()は引数にFunctionを持つ

インタフェースFunction
T…引数の型
R…戻り値の型

applyがいきなりつかえるのは何故か?
インターフェイスFunctionの中にはapplyしかメソッドがないため(defaultは無視される)

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1