Created
September 22, 2015 05:09
-
-
Save mmts1007/6c1daf62d8fd167ae98c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
public class HelloStreaming { | |
public static void main(String... args) { | |
List<String> numbers = Arrays.asList("4", "5", "1", "2", "3", "4", "5"); | |
// map | |
numbers.stream().map(num -> Integer.parseInt(num)) // String型をInteger型に変換(マッピング)する | |
.forEach(num -> System.out.print(num)); // マッピングした各要素を表示する | |
// filter | |
numbers.stream().mapToInt(num -> Integer.parseInt(num)) // オブジェクト型の要素をint型にマッピング | |
.filter(num -> num % 2 == 0) // 引数に指定した処理でフィルタリング | |
.forEach(num -> System.out.print(num)); // フィルタリング結果を表示 | |
// distinct | |
numbers.stream().distinct() // 重複の排除 | |
.forEach(num -> System.out.print(num)); | |
// sort | |
numbers.stream().sorted() // ソート | |
.forEach(num -> System.out.print(num)); | |
// forEach | |
numbers.stream().forEach(num -> System.out.print(num)); // 各要素を表示する | |
// count | |
numbers.stream().map(num -> Integer.parseInt(num)).count(); | |
// collect | |
// ストリームの要素を collect(集約) する | |
// 今回は Collectors.toList() によってリストに集約 | |
List<Integer> integerNumbers = numbers.stream().map(num -> Integer.parseInt(num)).collect(Collectors.toList()); | |
// 日本語的に記述することができる | |
numbers.stream().map(Integer::parseInt) // Integer型に変換し | |
.filter(num -> num % 2 == 0) // 値が偶数の要素を | |
.sorted() // ソートして | |
.collect(Collectors.toList()); // List に集約する | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment