以前にもちょっと扱ったJavaのStreamに関してまとめ
過去のリンク
MapのStream
http://skill-up-engineering.com/?p=642
streamを使ったカウント&合計
http://skill-up-engineering.com/?p=389
foreach,fitlter,anymatch,groupByなどについて
http://skill-up-engineering.com/?p=329
ソース
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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
public class Practice { List<Student> students; public Practice() { students = new ArrayList<>(); students.add(new Student("tarou", 23, "hoge@gmail.com", Pref.TOKYO)); students.add(new Student("jirou", 33, "foo@hotmail.com", Pref.KANAGAWA)); students.add(new Student("saburou", 26, "bar@yahoo.co.jp", Pref.CHIBA)); students.add(new Student("shirou", 43, "aaa@exampl.com", Pref.TOKYO)); students.add(new Student("gorou", 63, "bbb@gmail.com", Pref.TOKYO)); } /** * IntStreamの活用 */ public void Sample1() { IntStream.rangeClosed(1, 10) //1~10までのIntStream .filter(i -> i % 2 == 0) //偶数に対して .forEach(s -> System.out.println(s)); } /** * Streamの活用(Mapを使った変換) */ public void Sample2() { students.stream() .map(s -> s.getName() + s.getAge().toString()) .forEach(s -> System.out.println(s)); } /** * 最大値最小値の活用 */ public void Sample3() { OptionalInt maxVal = students.stream() .mapToInt(s -> s.getAge()) .max(); maxVal.ifPresent(a -> System.out.print(a)); } /** * filter & Listへの格納 */ public void Sample4() { List<Student> stundents2 = students.stream() .filter(s -> s.getAge() >= 30) .collect(Collectors.toList()); stundents2.stream().forEach(s -> System.out.println(s.getName() + s.getAge())); } /** * groupBy */ public void Sample5() { Map<Pref, List<Student>> stundents2 = students.stream() .collect(Collectors.groupingBy(s -> s.getPref())); System.out.print("この上でdebug"); } /** * groupBy */ public void Sample6() { students.stream() .collect(Collectors.groupingBy(s -> s.getPref())) .forEach((p, l) -> { System.out.println(p); l.stream().forEach(s -> System.out.println(s.getName() + s.getEmail() + s.getAge())); System.out.println(); }); } /** * groupBy + sum */ public void Sample7() { students.stream() .collect(Collectors.groupingBy(s -> s.getPref())) .forEach((p, l) -> { System.out.println(p); Student s = l.stream().max(Comparator.comparing(Student::getAge)).get(); System.out.print(s.getName() + s.getAge()); System.out.println(); }); } } |
注意事項
・加工した変数を追加した場合foreachの中でデバッグがうまくできないことがある(stream処理は逐一、処理を行っているわけではなく、終端操作が呼び出されるまで操作の実行が遅延されるため)
1 2 3 4 5 6 |
Elements elTd = ~ Actresses actressess = new Actresses(); elTd.stream().map((el) -> getActressProp(el)) .filter((actress) -> (actress != null)) //例えば下記のactressessにブレークポイントをおいてデバッグしてもループ中は内部が見えない .forEach((actress) -> actressess.addActresses(actress)); |