Stream API
データソースに対して様々な処理を行うAPI。 集計処理や加工が目的
How to use
- Streamの取得
- 中間操作
- 終端操作 いわばパイプライン処理と言える。
How to get
- stream() on Collection / Arrays
- lines() on Files / BufferedReader
- of() on Stream
forEach(Consumer)
- forEach
- forEachOrdered ... ensure input order
StreamAPI 種類
- filter(Predicate<? super T> predicate) : 条件に合致する要素を抽出する。
- map(<? super T, ? extends R>) : 要素を別の型に変換する。mappingって感じ
- peek(Consumer<? super T> action):要素の変更はなく、中間操作の確認のためのデバッグ用メソッド
allMatch(Predicate)
하나라도 틀리면 false
Predicate<String> test = n -> { System.out.println("Checking ... / "); return n.contains("ld"); }; list.stream().filter(c -> c.length() > 5).allMatch(test);
Collectors
List<Employee> emp = Arrays.asList( new Employee("101", "woosyume1", "Osaka"), new Employee("102", "woosyume2", "Tokyo"), new Employee("103", "woosyume3", "Osaka") ); emp.stream().collect(Collectors.groupingBy(Employee::getLoc)) .forEach((src, res) -> System.out.println(res));
[Employee [id=102, loc=Tokyo, name=woosyume2]] [Employee [id=101, loc=Osaka, name=woosyume1], Employee [id=103, loc=Osaka, name=woosyume3]]
이 때 src는 소스...getLoc의 값
peek
list.stream().map(f).peek(a -> System.out.println(a)); // peek만으로는 아무것도 표시되지 않는다. 중간처리이기 때문에