Java 8 stream API to kotlin collection API

Time:2021-12-29

The API for collection operations provided by kotlin is much simpler than that of Java 8 stream.

The following is the transformation from Java 8 stream API to kotlin collection API.

Map attributes aggregated into lists

Java

List names = users.stream().map(User::getName).collect(Collectors.toList());

kotlin

val list = user. Map {it. Name} / / tolist() is not required, which is very concise

Convert elements to strings and link them with commas/

Java

String joined = users.stream().map(User::toString).collect(Collectors.joining(", "));

Kotlin

val joined = users.joinToString(", ")

Calculate total salary

Java

int total = employees.stream()
.collect(Collectors.summingInt(Employee::getSalary)));

Kotlin

val total = employees.sumBy { it.salary }

grouping

Java

Map> byDept = employees.stream().collect(Collectors.groupingBy(Employee::getDepartment));

Kotlin

val byDept = employees.groupBy { it.department }

Grouping statistics

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 }}

Slice

Java

Map> passingFailing = students.stream().collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));

Kotlin

val passingFailing = students.partition { it.grade >= PASS_THRESHOLD }

Filter mapping

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 }

Grouping elements

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 } }

Filter list elements

Java

List filtered = items.stream()
.filter( item -> item.startsWith("o") )
.collect(Collectors.toList());

Kotlin

val filtered = items.filter { it.startsWith('o') }

Find the shortest string in the list

Java

String shortest = items.stream()
.min(Comparator.comparing(item -> item.length()))
.get();

Kotlin

val shortest = items.minBy { it.length }

Filter the list and count the total

Java

long count = items.stream().filter( item -> item.startsWith("t")).count();

Kotlin

val count = items. filter { it.startsWith('t') }. size

Original link

Kotlin converts objects to maps_ Java 8 stream API to kotlin collection API

This work adoptsCC agreement, reprint must indicate the author and the link to this article