How can I call collect(Collectors.toList()) on a Java 8 Stream in Kotlin?

后端 未结 2 2015
时光取名叫无心
时光取名叫无心 2020-12-11 04:15

I have the some code:

directoryChooser.title = \"Select the directory\"
val file = directoryChooser.showDialog(null)
if (file != null) {
    var files = File         


        
2条回答
  •  一个人的身影
    2020-12-11 04:46

    This is another work around if you are for some reason stuck on older beta version of Kotlin which requires a more brutal workaround...

    Workaround #3: (ugly, an old workaround ONLY for old versions of Kotlin)

    Add this Java class to your project:

    import java.util.List;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class CollectFix {
        public static  List streamToList(Stream s) {
            return s.collect(Collectors.toList());
        }
    }
    

    And this one Kotlin extension function:

    fun  Stream.toList(): List = CollectFix.streamToList(this)
    

    And then any time you have this case, use this new extension:

    Files.list(Paths.get(file)).filter { /* filter clause */ }.toList()
    

提交回复
热议问题