2020年1月アーカイブ

今更だけどJava8,9以降で導入されているstream APIの復習。普段の参加するプロジェクトでは古いコードをそのまま継承しているので、stream式が全く出てこない。しかし、一般のJava界隈で従来のCollectionに替わりstream式で実装するのがほぼ日常となっている。

StreamAPIを復習する。
Springの参考書籍として、イタリアRedHat所属の Mario Fusco 氏による「Modern Java in Action」が洋書ながらとても分かりやすく、参考コードもとても分かりやすいのでこれを参考とした。

chap5 辺り

// Filtering with predicate
  System.out.println("Filtering with a predicate");
  List<Dish> vegetarianMenu = menu.stream()
     .filter(Dish::isVegetarian)
     .collect(toList());
  vegetarianMenu.forEach(System.out::println);

List<Dish> menu は、
bean として、public class Dish の静的固定 List メンバー変数として以下を定義している。

public static final List<Dish> menu = Arrays.asList(
new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("chicken", false, 400, Dish.Type.MEAT),
new Dish("french fries", true, 530, Dish.Type.OTHER),
new Dish("rice", true, 350, Dish.Type.OTHER),
new Dish("season fruit", true, 120, Dish.Type.OTHER),
new Dish("pizza", true, 550, Dish.Type.OTHER),
new Dish("prawns", false, 400, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH)
);

☞ menu.stream() で別のListに代入しつつ、

.filter(Dish::isVegetarian)
.collect(toList());

.filter で isVegetarian で、private final boolean vegetarian; がtrueのみ抽出している。

.collect(toList());
で別の List<Dish> に集約

Filterling_a_stream_with_a_predicate_.jpg

//////////////  Bean //////////////////////////////////////////////////////////////////////////////////////////////

public class Dish {

private final String name;
private final boolean vegetarian;
private final int calories;
private final Type type;

public Dish(String name, boolean vegetarian, int calories, Type type) {
this.name = name;
this.vegetarian = vegetarian;
this.calories = calories;
this.type = type;
}

public String getName() {
return name;
}

public boolean isVegetarian() {
return vegetarian;
}

public int getCalories() {
return calories;
}

public Type getType() {
return type;
}

public enum Type {
MEAT,
FISH,
OTHER
}

このアーカイブについて

このページには、2020年1月に書かれたブログ記事が新しい順に公開されています。

前のアーカイブは2019年10月です。

次のアーカイブは2020年11月です。

最近のコンテンツはインデックスページで見られます。過去に書かれたものはアーカイブのページで見られます。