Java 8 Stream API 转换到 Kotlin 集合API

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 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!