Stream API の anyMatch, allMatch の使い方メモ
サンプルソース
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
package smaple; import java.util.ArrayList; import java.util.List; /** * サンプルクラス. */ public class MainTest { /** * メイン * @param args 引数 */ public static void main(String[] args) { // リスト生成 List<TestDataset> list = new ArrayList<TestDataset>(); list.add(new TestDataset("テスト1", 1)); list.add(new TestDataset("テスト2", 2)); list.add(new TestDataset("テスト3", 3)); // 以下値のデータセット抽出 final int val = 2; // 含まれているかチェック boolean isExists = list.stream().anyMatch(d -> val == d.value); // コンソール出力 System.out.println(String.format("isExists = %s", isExists)); System.out.println("--------------------------------------"); // -------------------------------- // 全てのリストに含まれているかチェック boolean isAllExists = list.stream().allMatch(d -> val == d.value); // コンソール出力 System.out.println(String.format("isAllExists = %s", isAllExists)); } /** * テスト用データセット. */ public static class TestDataset { /** 名称. */ public String name; /** 値. */ public int value; /** * コンストラクタ. * @param name 名称 * @param value 値 */ public TestDataset(String name, int value) { this.name = name; this.value = value; } } } |
コンソール出力
1 2 3 |
isExists = true -------------------------------------- isAllExists = false |
以上です☆