Kotlin提供的集合操作的API相對Java 8 Stream的API簡潔很多。
下面是Java 8 Stream API轉換到Kotlin集合API。
對映屬性聚合為列表
Java
List names = users.stream().map(User::getName).collect(Collectors.toList());
kotlin
val list = user.map { it.name } // 不需要toList(),很簡潔
轉換元素為字串並用逗號連結/
Java
String joined = users.stream().map(User::toString).collect(Collectors.joining(", "));
Kotlin
val joined = users.joinToString(", ")
計算薪資總數
Java
int total = employees.stream()
.collect(Collectors.summingInt(Employee::getSalary)));
Kotlin
val total = employees.sumBy { it.salary }
分組
Java
Map> byDept = employees.stream().collect(Collectors.groupingBy(Employee::getDepartment));
Kotlin
val byDept = employees.groupBy { it.department }
分組統計
Java
Map totalByDept = employees.stream().collect(Collectors.groupingBy(Employee::getDepartment, Collectors.summingInt(Employee::getSalary)));
Kotlin
val totalByDept = employees.groupBy { it.dept }.mapValues { it.value.sumBy { it.salary }}
分片
Java
Map> passingFailing = students.stream().collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));
Kotlin
val passingFailing = students.partition { it.grade >= PASS_THRESHOLD }
過濾對映
Java
List namesOfMaleMembers = roster.stream().filter(p -> p.getGender() == Person.Sex.MALE).map(p -> p.getName()).collect(Collectors.toList());
Kotlin
val namesOfMaleMembers = roster.filter { it.gender == Person.Sex.MALE }.map { it.name }
分組元素
Java
Map namesByGender = roster.stream()
.collect(Collectors.groupingBy(Person::getGender,
Collectors.mapping(Person::getName, Collectors.toList())));
Kotlin
val namesByGender = roster.groupBy { it.gender }.mapValues { it.value.map { it.name } }
過濾列表元素
Java
List filtered = items.stream()
.filter( item -> item.startsWith("o") )
.collect(Collectors.toList());
Kotlin
val filtered = items.filter { it.startsWith('o') }
查詢列表最短的字串
Java
String shortest = items.stream()
.min(Comparator.comparing(item -> item.length()))
.get();
Kotlin
val shortest = items.minBy { it.length }
過濾列表並統計總數
Java
long count = items.stream().filter( item -> item.startsWith("t")).count();
Kotlin
val count = items.filter { it.startsWith('t') }.size
// 不需要filter直接統計
val count = items.count { it.startsWith('t') }
原文連結
kotlin將物件轉換為map_Java 8 Stream API轉換到Kotlin集合API
本作品採用《CC 協議》,轉載必須註明作者和本文連結