zoukankan      html  css  js  c++  java
  • How to merge Scala Lists

    Scala List FAQ: How do I merge a List in Scala?

    NOTE: I wrote the solutions shown below a long time ago, and they are not optimal. I'll update this article when I have more time. The best approach is to prepend one List to the beginning of another List with the :: method.

    There are at least three ways to merge/concatenate Scala List instances, as shown in the examples below.

    1) The Scala List ::: method

    First, you can merge two Scala lists using the ::: method of the List class, as demonstrated here at the Scala command prompt:

    scala> val a = List(1,2,3)
    a: List[Int] = List(1, 2, 3)
    
    scala> val b = List(4,5,6)
    b: List[Int] = List(4, 5, 6)
    
    scala> val c = a ::: b
    c: List[Int] = List(1, 2, 3, 4, 5, 6)
    

    This operation is said to have O(n) speed, where n is the number of elements in the first List.

    2) The Scala List concat method

    You can also merge two Scala lists using the List class concat method:

    scala> val a = List(1,2,3)
    a: List[Int] = List(1, 2, 3)
    
    scala> val b = List(4,5,6)
    b: List[Int] = List(4, 5, 6)
    
    scala> val c = List.concat(a, b)
    c: List[Int] = List(1, 2, 3, 4, 5, 6)
    

    3) The Scala List ++ method

    You can also use the List ++ method to concatenate Scala Lists, as shown here:

    scala> val a = List(1,2,3)
    a: List[Int] = List(1, 2, 3)
    
    scala> val b = List(4,5,6)
    b: List[Int] = List(4, 5, 6)
    
    scala> val c = a ++ b
    c: List[Int] = List(1, 2, 3, 4, 5, 6)
    

    I'll try to add more information on these three approaches as I learn about them, but for now, I just wanted to share these three approaches.

  • 相关阅读:
    ubuntu16.04搭建jdk1.8运行环境
    window如何查看被占用端口的使用情况
    Windows下80端口被进程System占用的解决方法
    java.lang.OutOfMemoryError:PermGen space tomcat7 内存溢出
    GitLab服务器IP地址修改
    Ubuntu输入ifconfig找不到IP地址,只有lo问题
    git命令如何删除文件或文件夹
    数组转List
    Java NIO 缓冲区
    MySQL数据类型-整型
  • 原文地址:https://www.cnblogs.com/seaspring/p/5645195.html
Copyright © 2011-2022 走看看