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

5分で分かるかもしれないjava8 Stream API

5分で分かるかもしれないjava8 Stream API

Kazuhiro Serizawa

November 26, 2015
Tweet

More Decks by Kazuhiro Serizawa

Other Decks in Programming

Transcript

  1. 5෼Ͱ෼͔Δ͔΋͠Εͳ͍ java8 Stream API

  2. java8ʹ͍ͭͯ • 2014೥3݄18೔ʹOracle͔Βެ։ • “ੈքҰͷ։ൃϓϥοτϑΥʔϜͷըظతͳϦϦʔ ε” ※OracleେຊӦൃද • ϥϜμࣜɺStreamAPIɺDate and

    Time APIͳͲͷ ৽ػೳͷಋೖͰjavaքʹֵ໋͕ʂ
 ʢͱࢥ͚ͬͨͲͦ͜·Ͱ੝Γ্͕Βͳ͔ͬͨʣ
  3. ࠓ೔͸̑෼͔͠ͳ͍ͷͰ • Stream APIʹ͍ͭͯ֓ཁΛ࿩͠·͢ • ʮjava΋গ͠͸ϚγʹͳͬͨΑ͏ͩͳʯ
 ͱ͍͏ͷΛײ͡औͬͯ΋Β͑Ε͹޾͍Ͱ͢

  4. Stream APIͱ͸ʁ • ഑ྻɺϦετͳͲͷෳ਺ͷσʔλʹ͓͚Δू ໿ૢ࡞ͷαϙʔτΛߦ͏API • ฒߦॲཧ΍ΒͷϕϯϦػೳΛఏڙͯ͘͠ΕΔ UtilͰ͸ͳ͘Interface͚ͩΛఏڙ͢Δ

  5. Stream APIͱ͸ʁ • ཁ͢ΔʹRubyͰݴ͏ͱ͜Ζͷ • Enumerable#each • Enumerable#select • Enumerable#map

    • ͜ΕΒͷॲཧΛʮܾ·ͬͨखॱͰ࣮ߦ͢ΔʯAPI • Stream API ≠࣮૷ɻInterfaceͷΈΛఆ͍ٛͯ͠Δɻ
  6. StreamΛ࢖Θͳ͍৔߹ͷྫ List<Integer> list = Arrays.asList(1,2,3);
 Integer result = 0;
 for

    (Integer i : list) {
 result += i * i;
 }
 System.out.println(result); //14
  7. ͳ͓ruby result = [1,2,3]
 .map{ |i| i*i }
 .inject{ |a,b|

    a + b }
 puts result #=> 14
  8. StreamΛ࢖͏৔߹ͷྫ List<Integer> list = Arrays.asList(1,2,3);
 Integer result = list.stream()
 .map(x

    -> x * x)
 .reduce((a, b) -> a + b)
 .get();
 System.out.println(result); //14
  9. Stream APIΛ༻͍࣮ͨ૷ "SSBZ -JTUͳͲͷ
 %BUBTPVSDF TUSFBN࡞੒ தؒૢ࡞
 ϑΟϧλϦϯάɾ஋ͷૢ࡞ͳͲ ऴ୺ૢ࡞
 ू໿ૢ࡞ɾผΫϥε΁ͷม׵ɾ


    ஞ࣍ॲཧͳͲ ॲཧ͞Εͨ݁Ռ list.stream()
 
 
 .map(x -> x * x)
 
 .reduce((a, b) -> a + b) .get();
  10. ඪ४ϥΠϒϥϦ with Stream Stream<String> lines = Files.lines(path)
 lines.filter(line -> line.startsWith(“a”))


    .map(s -> s.toUpperCase)
 .forEach(s -> System.out.println(s));
 // “AMAZON”
 // “ATOM”
  11. StreamʹΑͬͯԿ͕͏Ε͍͔͠ • σʔλϦιʔεૢ࡞ͷ࣮૷ͷ؆ུԽ • ϥϜμࣜͱ૊Έ߹ΘͤΔ͜ͱͰ
 ؔ਺ܕͬΆ͍syntaxʹ • σʔλϦιʔεʹର͢Δฒߦॲཧɾ෼ࢄॲཧ Λstream()ϝιουʹӅṭԽ࣮ͯ͠૷Ͱ͖Δ

  12. Collection frameworkͩͱ
 ϚϧνεϨουͰฒߦॲཧ͢ΔstreamΛ࡞ΕΔ List<Integer> list = Arrays.asList(1,2,3);
 Integer result =

    list.parallelStream()
 .map(x -> x * x)
 .reduce((a, b) -> a + b)
 .get();
 System.out.println(result); //14
  13. ༨ஊɿ
 Apache SparkΛ࢖ͬͨ෼ࢄॲཧ࣮૷ input.
 flatMap(line -> Arrays.asList(line.split("\\s+")))
 .mapToPair(word -> new

    Tuple2(word, 1))
 .reduceByKey((x, y) -> (Integer) x + (Integer) y)
 .sortByKey()
 .collect();
  14. Stream APIͷ·ͱΊ • ීஈྑ͘࢖͏Collection Frameworkͷॲཧ͕ γϯϓϧʹ࣮૷Ͱ͖ΔΑ͏ʹͳΔ • ruby೴ʹ΋༏͍͠ • ෼ࢄɾฒߦॲཧΛӅṭԽ࣮ͯ͠૷Ͱ͖ͦ͏ͳ

    ઃܭํ਑Λ͍ࣔͯ͠Δ