LoginSignup
0
0

More than 3 years have passed since last update.

Java8 ラムダ式を変数に代入して再利用する

Posted at

ラムダ式はオブジェクトと同じように、変数に代入して再利用ができます。
filter() メソッドを例にして、ラムダ式を変数に代入して再利用してみます。
以下のリストから、8文字以上の文字列のみをフィルタで取り出してみたいと思います。

final List<String> months = 
Arrays.asList("January", "February", "March", "April", "May", "June", "July", "Augast", "September", "October", "November", "December");

final List<String> jewelries = 
Arrays.asList("garnet", "amethyst", "aquamarine", "diamond", "emerald", "pearl", "ruby", "sardonyx", "sapphire", "opal", "topaz", "turquoise");

8文字以上の文字列のみをフィルタするラムダ式を longName 変数に代入します。

final Predicate<String> longName = name -> name.length() >= 8;

以下のように2つの別々のリストの filter() 式に対して、同じ変数(longName)に代入したラムダ式を適用しています。

// フィルタして出力する
final List<String> longNameMonths = months.stream().filter(longName).collect(Collectors.toList());
final List<String> longNameJewelries = jewelries.stream().filter(longName).collect(Collectors.toList());

longNameMonths.forEach(System.out::println);
longNameJewelries.forEach(System.out::println);

結果、以下のように8文字以上の文字列のみが出力されました。

February
September
November
December
amethyst
aquamarine
sardonyx
sapphire
turquoise
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