0
0

(java gold) mapメソッド

Posted at

map

  • ストリーム内の要素を別の値に変更する際に使用
  • 基本的な構文は以下の通りである
stream.map(function)
  • stream : 元のストリームを表す
  • map()メソッド : Function型の引数を受け取る
  • function : 各要素を変更するための関数
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> doubledNumbers = numbers.stream()
                                      .map(number -> number * 2)
                                      .collect(Collectors.toList());

numbersという整数のリストを作成し、mapメソッドを使って各要素を2倍に変換している。この場合、ラムダ式number -> number * 2がFunction型の引数として渡され、各要素が2倍になった新しいストリームが生成する

mapToInt,mapToLong,mapToDouble,mapToObj

mapにはint型に変換するmapToInt,long型に変換するmapToLong,double型に変換するmapToDouble,Object型に変換するmapToObjが存在する。

List<String> nums = asList("1", "2", "3");

int sum = nums.stream()
            .mapToInt(Integer::parseInt)
            .filter(i -> i % 2 == 1)
            .sum();
0
0
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
0
0