Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Stream API 入門 #jjug #javajo

Stream API 入門 #jjug #javajo

Java女子部「Java本格入門!!!著者をお招きしちゃうよ(*´∀`*) 」
https://javajo.doorkeeper.jp/events/60742

JJUG ナイトセミナー 「Java エンジニアのためのJava(再)入門」
https://jjug.doorkeeper.jp/events/61857

Shin Tanimoto

June 11, 2017
Tweet

More Decks by Shin Tanimoto

Other Decks in Programming

Transcript

  1. List<Student> students = new ArrayList<>(); students.add(new Student("Ken", 100)); students.add(new Student("Shin",

    60)); students.add(new Student("Takuya", 80)); for (Student student : students) { if (student.getScore() >= 70) { System.out.println(student); } } ͜Ε͕
  2. List<Student> students = new ArrayList<>(); students.add(new Student("Ken", 100)); students.add(new Student("Shin",

    60)); students.add(new Student("Takuya", 80)); 
 students.stream() .filter(s -> s.getScore() >= 70) .forEach(System.out::println); ͜͏ͳΔ
  3. Map<Dept, Long> groupByDeptAndFilter(List<Emp> list) { return list.stream() .collect(Collectors.groupingBy(emp -> emp.dept))

    .entrySet() .stream() .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue() .stream() .filter(emp -> emp.sal > 1000) .count())); }
  4. Map<Dept, Long> groupByDeptClassic(List<Emp> list) { Map<Dept, Long> result = new

    HashMap<>(); for (Emp emp : list) { if (result.containsKey(emp.dept) == false) { result.put(emp.dept, 0L); } if (emp.sal > 1000) { Long count = result.get(emp.dept); count++; result.put(emp.dept, count); } } return result; }
  5. List<Student> students = new ArrayList<>(); students.add(new Student("Ken", 100)); students.add(new Student("Shin",

    60)); students.add(new Student("Takuya", 80)); 
 students.stream() .filter(s -> s.getScore() >= 70) .forEach(System.out::println); ͜ͷ෦෼
  6. void sort() { List<Student> studentList = new ArrayList<>(); studentList.add(new Student("Murata",

    100)); studentList.add(new Student("Okada", 70)); studentList.add(new Student("Tanimoto", 80)); System.out.println(studentList); Collections.sort(studentList, new StudentComparator()); System.out.println(studentList); } class StudentComparator implements Comparator<Student> { @Override public int compare(Student student1, Student student2) { return Integer.compare(student1.getScore(), student2.getScore()); } } ͜ͷ෦෼
  7. void sortAnonymous() { List<Student> studentList = new ArrayList<>(); studentList.add(new Student("Murata",

    100)); studentList.add(new Student("Okada", 70)); studentList.add(new Student("Tanimoto", 80)); System.out.println(studentList); Collections.sort(studentList, new Comparator<Student>() { @Override public int compare(Student student1, Student student2) { return Integer.compare(student1.getScore(), student2.getScore()); } }); System.out.println(studentList); } ແ໊ΫϥεΛ࢖͏ͱ
  8. void sortLambda() { List<Student> studentList = new ArrayList<>(); studentList.add(new Student("Murata",

    100)); studentList.add(new Student("Okada", 70)); studentList.add(new Student("Tanimoto", 80)); System.out.println(studentList); Collections.sort(studentList, (student1, student2) -> Integer.compare(student1.getScore(), student2.getScore())); System.out.println(studentList); } -BNCEBΛ࢖͏ͱ
  9. List<Student> students = new ArrayList<>(); students.add(new Student("Ken", 100)); students.add(new Student("Shin",

    60)); students.add(new Student("Takuya", 80)); 
 students.stream() .filter(s -> s.getScore() >= 70) .forEach(System.out::println); ΋͜͠Ε͕
  10. List<Student> students = new ArrayList<>(); students.add(new Student("Ken", 100)); students.add(new Student("Shin",

    60)); students.add(new Student("Takuya", 80)); students.stream() .filter(new Predicate<Student>() { @Override public boolean test(Student student) { return student.getScore() >= 70; } }) .forEach(new Consumer<Student>() { @Override public void accept(Student student) { System.out.println(student); } }); ͜͏ͳΒ
  11. (Student student1, Student student2) -> { int score1 = student1.getScore();

    int score2 = student2.getScore(); return Integer.compare(score1, score2); } (Student student) -> {
 System.out.println(student); } () -> {
 System.out.println("Hello!"); }
  12. (Student student1, Student student2) -> { int score1 = student1.getScore();

    int score2 = student2.getScore(); return Integer.compare(score1, score2); } (student1, student2) -> { int score1 = student1.getScore(); int score2 = student2.getScore(); return Integer.compare(score1, score2); }
  13. (student1, student2) -> { int score1 = student1.getScore(); int score2

    = student2.getScore(); return Integer.compare(score1, score2); } 
 
 (student1, student2) -> { return Integer.compare(student1.getScore(), student2.getScore()); } (student1, student2) -> Integer.compare(student1.getScore(), student2.getScore())
  14. (Student student) -> {
 System.out.println(student); } 
 
 
 student

    -> System.out.println(student) System.out::println
  15. (Student student) -> {
 return student.getScore(); } 
 
 


    student -> student.getScore(); Student::getScore
  16. List<Student> students = new ArrayList<>(); students.add(new Student("Ken", 100)); students.add(new Student("Shin",

    60)); students.add(new Student("Takuya", 80)); 
 students.stream() .filter(s -> s.getScore() >= 70) .forEach(System.out::println); ݁Ռɺ͜͏ͳΔ
  17. List<String> lines = Arrays.asList("Murata=100", "Okada=60", "Tanimoto=80"); List<Student> students = lines.stream()

    .map(s -> { String[] strings = s.split("="); return new Student(strings[0], Integer.valueOf(strings[1])); }) .filter(s -> s.getScore() >= 70) .collect(Collectors.toList()); $PMMFDUJPOTUSFBN
  18. String[] lines = {"Murata=100", "Okada=60", "Tanimoto=80"}; List<Student> students = Arrays.stream(lines)

    .map(s -> { String[] strings = s.split("="); return new Student(strings[0], Integer.valueOf(strings[1])); }) .filter(s -> s.getScore() >= 70) .collect(Collectors.toList()); "SSBZTTUSFBN
  19. List<String> lines = Arrays.asList("Murata=100", "Okada=60", "Tanimoto=80"); List<Student> students = lines.stream()

    .map(s -> { String[] strings = s.split("="); return new Student(strings[0], Integer.valueOf(strings[1])); }) .filter(s -> s.getScore() >= 70) .collect(Collectors.toList()); } NBQͱpMUFS
  20. List<String> lines = Arrays.asList("Murata=100", "Okada=60", "Tanimoto=80"); List<Student> students = lines.stream()

    .map(s -> { String[] strings = s.split("="); return new Student(strings[0], Integer.valueOf(strings[1])); })
 // この時点でStudentのstreamになる .filter(s -> s.getScore() >= 70) // この時点でMurataとTanimotoが残ったstreamになる .collect(Collectors.toList()); } NBQͱpMUFS
  21.          ͔Β

             ͸࡞ΕΔ
  22. List<String> lines = Arrays.asList("Murata=100", "Okada=60", "Tanimoto=80"); List<Student> students = lines.stream()

    .map(s -> { String[] strings = s.split("="); return new Student(strings[0], Integer.valueOf(strings[1])); }) .filter(s -> s.getScore() >= 70) .collect(Collectors.toList()); } DPMMFDU
  23. String[] lines = {"Murata=100", "Okada=60", "Tanimoto=80"}; Map<String, Student> students =

    Arrays.stream(lines) .map(s -> { String[] strings = s.split("="); return new Student(strings[0], Integer.valueOf(strings[1])); }) .collect(Collectors.toMap(s -> s.getName(), s -> s)); return students; $PMMFDUPSTUP.BQ
  24. List<Transaction> list = new ArrayList<>(); try (BufferedReader reader = Files.newBufferedReader(Paths.get(fileName)))

    { String line; while ((line = reader.readLine()) != null) { String[] s = line.split(","); Transaction tx = new Transaction(); tx.date = LocalDate.parse(s[0]); tx.accountId = s[1]; tx.amount = Integer.valueOf(s[2]); tx.name = s[3]; tx.note = s[4]; list.add(tx); } } catch (IOException e) { throw new RuntimeException("failed to parse date or read file", e); } return list; GSPN
  25. try (Stream<String> stream = Files.lines(Paths.get(fileName))) { return stream .map(line ->

    { String[] s = line.split(","); Transaction tx = new Transaction(); tx.date = LocalDate.parse(s[0]); tx.accountId = s[1]; tx.amount = Integer.valueOf(s[2]); tx.name = s[3]; tx.note = s[4]; return tx; }) .collect(Collectors.toList()); } catch (IOException e) { throw new UncheckedIOException("failed to read file", e); } UP4USFBN
  26. try (Stream<String> stream = Files.lines(Paths.get(fileName))) { return stream .map(line ->

    { String[] s = line.split(","); Transaction tx = new Transaction(); tx.date = LocalDate.parse(s[0]); tx.accountId = s[1]; tx.amount = Integer.valueOf(s[2]); tx.name = s[3]; tx.note = s[4]; return tx; }) .collect(Collectors.toList()); } catch (IOException e) { throw new UncheckedIOException("failed to read file", e); } UP4USFBN ϑΝΠϧΛಡΈࠐΜͰ
 Streamͱͯ͠ฦ͢ϝιου
 ʢߦ͝ͱʹॲཧʣ ߦͷStringΛ
 Transactionʹม׵ Listʹͯ͠ฦ͢
  27. // 取引履歴の取得 List<Transaction> list = read(fileName); // 全件表示 for (Transaction

    tx : list) { System.out.println(tx); } // 残高の計算 int sum = 0; for (Transaction tx : list) { sum += tx.amount; } System.out.println(sum); // 6月分のみ表示 for (Transaction tx : list) { if (tx.date.getMonth() == Month.JUNE) { System.out.println(tx); } } GSPN
  28. // 取引履歴の取得 read(fileName).stream() .forEach(System.out::println); // 残高の計算 int sum = read(fileName).stream()

    .mapToInt(tx -> tx.amount) .sum(); System.out.println(sum); // 6月分のみ表示 read(fileName).stream() .filter(tx -> tx.date.getMonth() == Month.JUNE) .forEach(System.out::println); UP4USFBN
  29. // 取引履歴の取得 read(fileName).stream() .forEach(System.out::println); // 残高の計算 int sum = read(fileName).stream()

    .mapToInt(tx -> tx.amount) .sum(); System.out.println(sum); // 6月分のみ表示 read(fileName).stream() .filter(tx -> tx.date.getMonth() == Month.JUNE) .forEach(System.out::println); UP4USFBN ͢΂ͯͷཁૉʹ͍ͭͯ
 ॱ൪ʹॲཧ औҾֹΛint஋ͱͯ͠औΓग़ͯ͠
 intͷstreamʢIntStreamʣʹ͔ͯ͠Β
 ߹ܭ஋Λऔಘ 6݄ͷΈΛऔΓग़ͯ͠
 શ݅දࣔ
  30. void monitorGauge(Flux<Double> input) { input.bufferTimeout(100, Duration.ofSeconds(10)) .subscribe(list -> { DoubleSummaryStatistics

    stats = list.stream() .mapToDouble(Double::doubleValue) .summaryStatistics(); if (stats.getMax() > maxThreshold) { alert(Level.WARNING); } if (stats.getAverage() > averageThreshold) { alert(Level.SEVERE); } }); } 3FBDUPSͷ"1*
  31. void monitorGauge(Flux<Double> input) { input.bufferTimeout(100, Duration.ofSeconds(10)) .subscribe(list -> { DoubleSummaryStatistics

    stats = list.stream() .mapToDouble(Double::doubleValue) .summaryStatistics(); if (stats.getMax() > maxThreshold) { alert(Level.WARNING); } if (stats.getAverage() > averageThreshold) { alert(Level.SEVERE); } }); } 3FBDUPSͷ"1* 100݅΋͘͠͸10ඵؒͷσʔλΛ
 ·ͱΊͯॲཧ͢Δ ʢूܭͯ͠ᮢ஋Λ௒͑ͨΒΞϥʔτʣ
  32. Mono<Map<Student, List<Score>>> map =
 studentService.fetchStudents("1年3組") .flatMap(student -> scoreService.fetchScore(2017, student.id)
 .collectList()

    .map(scores -> Tuples.of(student, scores))) .collectMap(Tuple2::getT1, Tuple2::getT2); // 出力 System.out.println(map.block());
 
 
 // 呼び出すAPI Flux<Student> fetchStudents(String className); Flux<Score> fetchScore(int year, int id) 3FBDUPSͷ"1*
  33. Mono<Map<Student, List<Score>>> map =
 studentService.fetchStudents("1年3組") .flatMap(student -> scoreService.fetchScore(2017, student.id)
 .collectList()

    .map(scores -> Tuples.of(student, scores))) .collectMap(Tuple2::getT1, Tuple2::getT2); // 出力 System.out.println(map.block());
 
 
 // 呼び出すAPI Flux<Student> fetchStudents(String className); Flux<Score> fetchScore(int year, int id) 3FBDUPSͷ"1* ʢৄࡉ͸ׂѪ͢Δ͚Ͳʣ
 APIݺͼग़͠ΛϊϯϒϩοΩϯά͔ͭ
 ඇಉظʹݺͼग़͢͜ͱͰ
 ॲཧશମͷ࣌ؒΛ୹ॖ
 ͔͠΋ར༻εϨου਺͕গͳ͍