Javaエンジニア養成読本 - 5日目
第3章 Stream APIを使いこなすために
Stream APIのサンプル
import java.util.Arrays; import java.util.List; import java.util.stream.IntStream; public class SampleClass { public static void main(String... args) { IntStream.rangeClosed(1, 10) .filter(n -> n % 2 == 0) .forEach(n -> System.out.println(n)); IntStream.rangeClosed(1, 10) .filter(n -> n % 2 == 0) .forEach(System.out::println); List<Student> students = Arrays.asList( new Student("Hoge"), new Student("Moge"), new Student("Fuga") ); students.stream() .map(s -> s.getName()) .forEach(n -> System.out.println(n)); students.stream() .map(Student::getName) .forEach(System.out::println); } } class Student { String name; Student(String name) { this.name = name; } String getName() { return name; } }
ファイルから数値列を読み込み最大値を求める
import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.OptionalInt; import java.util.stream.Stream; public class SampleClass { public static void main(String... args) { Path path = FileSystems.getDefault().getPath("data", "sample.txt"); try (Stream<String> s = Files.lines(path)) { int max = s.mapToInt(l -> Integer.parseInt(l)) .reduce(Integer.MIN_VALUE, (n, m) -> Integer.max(n, m)); System.out.println(max); } catch (IOException e) { System.out.println(e); } try (Stream<String> s = Files.lines(path)) { OptionalInt maxOpt = s.mapToInt(Integer::parseInt).max(); maxOpt.ifPresent(System.out::println); } catch (IOException e) { System.out.println(e); } } }
ディレクトリ以下に*.txtファイルが存在するかを判定する
import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; public class SampleClass { public static void main(String... args) { Path dir = FileSystems.getDefault().getPath("data"); try { System.out.println(containtsTextFile1(dir)); System.out.println(containtsTextFile2(dir)); } catch (IOException e) { System.out.println(e); } } public static boolean containtsTextFile1(Path dir) throws IOException { return Files.walk(dir) .filter(path -> Files.isRegularFile(path)) .map(path -> path.toString()) .anyMatch(name -> name.endsWith(".txt")); } public static boolean containtsTextFile2(Path dir) throws IOException { return Files.walk(dir) .filter(Files::isRegularFile) .map(Path::toString) .anyMatch(name -> name.endsWith(".txt")); } }
今日の感想
P.70まで。
今日は内容があまり把握できなかった。
サンプルコードを書くと意味はわかるが、記述されている内容を理解したかというと微妙。
明日復習する。