Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 lambda to kotlin lambda

Tags:

kotlin

public class Main {
    static class Account {
        private Long id;
        private String name;
        private Book book;

        public Account(Long id, String name, Book book) {
            this.id = id;
            this.name = name;
            this.book = book;
        }

        public String getName() {
            return name;
        }
    }
    public static void main(String[] args) {
        List<Account> data1 = new ArrayList<>();
        data1.add(new Account(1L,"name",null));
        List<String> collect = data1.stream().map(account -> account.getName()).collect(Collectors.toList());

        System.out.println(collect);
    }
}

In the above code I am trying to convert the following line

List<String> collect = data1.stream().map(account -> account.getName()).collect(Collectors.toList());

into kotlin code. Kotlin online editor gives me the following code

 val collect = data1.stream().map({ account-> account.getName() }).collect(Collectors.toList())
    println(collect)

which gives compilation error when i try to run it.

how to fix this???

or what is the kotlin way to get list of string from list of Account Object

like image 758
Mahabub Avatar asked Apr 30 '16 08:04

Mahabub


People also ask

Does lambda support Kotlin?

You can perform any operations on functions that are possible for other non-function values. To facilitate this, Kotlin, as a statically typed programming language, uses a family of function types to represent functions, and provides a set of specialized language constructs, such as lambda expressions.

What is a lambda expression when is the keyword it used in lambda in Kotlin?

Lambda expression is a simplified representation of a function. It can be passed as a parameter, stored in a variable or even returned as a value. Note: If you are new to Android app development or just getting started, you should get a head start from Kotlin for Android: An Introduction.


1 Answers

Kotlin collections don't have a stream() method.

As mentioned in https://youtrack.jetbrains.com/issue/KT-5175, you can use

(data1 as java.util.Collection<Account>).stream()...

or you can use one of the native Kotlin alternatives that don't use streams, listed in the answers to this question:

val list = data1.map { it.name }
like image 186
JB Nizet Avatar answered Sep 22 '22 19:09

JB Nizet