Reputation: 531
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
Upvotes: 5
Views: 2265
Reputation: 85946
As @JBNizet says, don't use streams at all, if you are converting to Kotlin then convert all the way:
List<String> collect = data1.stream().map(account -> account.getName()).collect(Collectors.toList());
to
val collect = data1.map { it.name } // already is a list, and use property `name`
and in other cases you will find that other collection types can become lists simply with toList()
or to a set as toSet()
and so on. And everything in Streams has an equivalent in Kotlin runtime already.
There is no need for Java 8 Streams at all with Kotlin, they are more verbose and add no value.
For more replacements to avoid Streams, read: What Java 8 Stream.collect equivalents are available in the standard Kotlin library?
You should read the following as well:
kotlin.collections
kotlin.sequences
And maybe this is a duplicate of: How can I call collect(Collectors.toList()) on a Java 8 Stream in Kotlin?
Upvotes: 1
Reputation: 691685
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 }
Upvotes: 12