Java/Stream API
StreamはJava 8で追加された、イテレーションの拡張API。
var result = data.stream()
.filter(s -> s.length() >= 5)
.count();
var strList = List.of("one", "two", "three");
var strArray = new String[]{"one", "two", "three"};
var stream1 = strList.stream();
var stream2 = Stream.of(strArray);
var stream3 = """
one
two
three
""".lines();
jshell> strList.stream().filter(s -> s.length() > 3).toList()
$17 ==> [three]
jshell> strList.stream().map(s -> s.toUpperCase()).toList()
$18 ==> [ONE, TWO, THREE]
jshell> strList.stream().skip(1).toList()
$19 ==> [two, three]
jshell> strList.stream().limit(2).toList()
$20 ==> [one, two]
jshell> strList.stream().sorted().toList()
$21 ==> [one, three, two]<
jshell> strList.stream().distinct().toList()
$22 ==> [one, two, three]/code>
jshell> strList.stream().toList() // Java 16で導入されたList化
$8 ==> [one, two, three]
jshell> strList.stream().count()
$9 ==> 3
jshell> strList.stream().allMatch(s -> s.contains("t")) // すべての要素が条件を満たすか
$10 ==> false
jshell> strList.stream().anyMatch(s -> s.contains("t")) // いずれかの要素が条件を満たすか
$11 ==> true
jshell> strList.stream().noneMatch(s -> s.contains("t")) // すべての要素が条件を満たさないか
$12 ==> false
jshell> strList.stream().forEach(s -> System.out.println(s))
one
two
three
jshell> strList.stream().collect(Collectors.joining())
$13 ==> "onetwothree"
jshell> strList.stream().collect(Collectors.joining("/"))
$14 ==> "one/two/three"
jshell> strList.stream().collect(Collectors.toList()) // Java 15以前のList化
$15 ==> [one, two, three]
jshell> var nums = new int[]{2, 5, 3}
nums ==> int[3] { 2, 5, 3 }
jshell> IntStream.of(nums).sum()
$2 ==> 10
jshell> IntStream.range(0, 10).toArray()
$3 ==> int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
jshell> IntStream.rangeClosed(0, 10).toArray()
$4 ==> int[11] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
jshell> IntStream.iterate(0, i -> i < 10, i -> i + 1).toArray()
$5 ==> int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }
jshell> IntStream.iterate(0, i -> (i * 211 + 2111) % 1000).limit(10).toArray()
$6 ==> int[10] { 0, 111, 532, 363, 704, 655, 316, 787, 168, 559 }
jshell> new Random().ints(10, 0, 100).toArray()
$7 ==> int[10] { 73, 65, 57, 42, 53, 15, 93, 54, 19, 28 }
jshell> IntStream.of(nums).map(n -> n * 2).toArray()
$8 ==> int[3] { 4, 10, 6 }
jshell> IntStream.of(nums).filter(n -> n < 5).toArray()
$9 ==> int[2] { 2, 3 }
jshell> IntStream.of(nums).sorted().toArray()
$10 ==> int[3] { 2, 3, 5 }
jshell> IntStream.of(nums).mapToObj(n -> "*".repeat(n)).toList()
$12 ==> [**, *****, ***]
jshell> strList.stream().mapToInt(s -> s.length()).toArray()
$13 ==> int[3] { 3, 3, 5 }