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
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With