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);
}
}在上面的代码中,我试图转换以下行
List<String> collect = data1.stream().map(account -> account.getName()).collect(Collectors.toList());进入kotlin密码。Kotlin在线编辑器给我以下代码
val collect = data1.stream().map({ account-> account.getName() }).collect(Collectors.toList())
println(collect)当我试图运行它时,会产生编译错误。
如何解决这个问题??
或者从帐户对象列表中获取字符串列表的kotlin方法是什么?
发布于 2016-05-09 22:11:50
正如@JBNizet所言,根本不要使用流,如果您要转换到Kotlin,那么就一直转换:
List<String> collect = data1.stream().map(account -> account.getName()).collect(Collectors.toList());至
val collect = data1.map { it.name } // already is a list, and use property `name`在其他情况下,您会发现其他集合类型可以简单地与toList()一起成为列表,或者成为一个集为toSet()等等。在Kotlin运行时中,流中的所有内容都具有等价性。
根本不需要使用Kotlin的Java 8流,它们更冗长,没有任何价值。
要获得更多的替换以避免流,请阅读:What Java 8 Stream.collect equivalents are available in the standard Kotlin library?
您还应该阅读以下内容:
kotlin.collections的Kotlin引用kotlin.sequences的Kotlin引用也许这是一个复制:How can I call collect(Collectors.toList()) on a Java 8 Stream in Kotlin?
https://stackoverflow.com/questions/36952815
复制相似问题