首页 文章

Java 8 lambda到kotlin lambda

提问于
浏览
5
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方式

2 回答

  • 10

    Kotlin集合没有 stream() 方法 .

    https://youtrack.jetbrains.com/issue/KT-5175中所述,您可以使用

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

    或者你可以使用一个不使用流的本机Kotlin替代品,列在this question的答案中:

    val list = data1.map { it.name }
    
  • 0

    正如@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() 等等 . Streams中的所有内容都已经在Kotlin运行时中具有相同的功能 .

    使用Kotlin完全不需要Java 8 Streams,它们更加冗长并且没有增加任何 Value .

    如需更多替换以避免Streams,请阅读:What Java 8 Stream.collect equivalents are available in the standard Kotlin library?

    您还应该阅读以下内容:

    也许这是一个副本:How can I call collect(Collectors.toList()) on a Java 8 Stream in Kotlin?

相关问题