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. Stream APIͱ͸ʁ • ཁ͢ΔʹRubyͰݴ͏ͱ͜Ζͷ • Enumerable#each • Enumerable#select • Enumerable#map

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

    (Integer i : list) {
 result += i * i;
 }
 System.out.println(result); //14
  3. 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
  4. Stream APIΛ༻͍࣮ͨ૷ "SSBZ -JTUͳͲͷ
 %BUBTPVSDF TUSFBN࡞੒ தؒૢ࡞
 ϑΟϧλϦϯάɾ஋ͷૢ࡞ͳͲ ऴ୺ૢ࡞
 ू໿ૢ࡞ɾผΫϥε΁ͷม׵ɾ


    ஞ࣍ॲཧͳͲ ॲཧ͞Εͨ݁Ռ list.stream()
 
 
 .map(x -> x * x)
 
 .reduce((a, b) -> a + b) .get();
  5. ඪ४ϥΠϒϥϦ 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”
  6. 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
  7. ༨ஊɿ
 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();