Java 8 lambda到kotlin lambda
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方式从Account Object列表中获取字符串列表
Kotlin集合没有stream()
方法。
正如https://youtrack.jetbrains.com/issue/KT-5175中提到的,您可以使用
(data1 as java.util.Collection<Account>).stream()...
或者可以使用本问题的答案中列出的不使用流的原生Kotlin替代方案之一:
val list = data1.map { it.name }
正如@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()
或toList()
等方式成为列表。 Streams中的所有内容都已经在Kotlin运行时中具有相同的功能。
Kotlin完全不需要Java 8 Streams,它们更加冗长,并且不增加任何价值。
有关避免Streams的更多替换,请阅读: 标准Kotlin库中的什么Java 8 Stream.collect等价物可用?
您还应该阅读以下内容:
-
kotlin.collections
Kotlin API参考 -
kotlin.sequences
Kotlin API参考
也许这是一个重复的: 如何在Kotlin的Java 8流上调用collect(Collectors.toList())?