scala初识04

map方法

Builds a new collection by applying a function to all elements of this

通过将函数应用于此元素的所有元素来构建新集合

package study2.collections

/**
  * @Author: mio
  * @Date: 2019/10/17 15:13
  */
object Main {
  def main(args: Array[String]): Unit = {
    //    val array = Array[Int](1, 2, 3, 4, 5, 6)
    //    array.foreach((x: Int) => println(x))
    //    array.foreach(println(_))
    //    array.foreach(println)

    val list = List(1, 2, 3, 4, 5, 6)
    //    普通的foreach写法
    //    list.foreach(println)
    //    进阶的写法
    list.map((x: Int) => println(x))
  }
}

flatmap方法

Builds a new collection by applying a function to all elements of this general collection and using the elements of the resulting collections. For example:

通过将函数应用于此常规集合的所有元素并使用所得集合的元素来构建新集合。例如:

def getWords(lines: Seq[String]): Seq[String] = lines flatMap (line => line split "\\W+")

The type of the resulting collection is guided by the static type of [Cannot find macro: $coll.] This might cause unexpected results sometimes. For example:

结果集合的类型由[找不到宏:$ coll。]的静态类型指导。这有时可能会导致意外结果。例如:

// lettersOf will return a Seq[Char] of likely repeated letters, instead of a Set
def lettersOf(words: Seq[String]) = words flatMap (word => word.toSet)

// lettersOf will return a Set[Char], not a Seq
def lettersOf(words: Seq[String]) = words.toSet flatMap (word => word.toSeq)

// xs will be an Iterable[Int]
val xs = Map("a" -> List(11,111), "b" -> List(22,222)).flatMap(_._2)

// ys will be a Map[Int, Int]
val ys = Map("a" -> List(1 -> 11,1 -> 111), "b" -> List(2 -> 22,2 -> 222)).flatMap(_._2)
package study2.collections

/**
  * @Author: mio
  * @Date: 2019/10/17 15:13
  */
object Main {
  def main(args: Array[String]): Unit = {
    val strings: List[String] = List[String]("minato aqua", "otogibara era", "nakiri ayame")
    val strings2 = strings.flatMap((x: String) => x.split(" "))
    strings2.foreach(println)
  }
}

flatMap是Map的一种扩展,Map主要将某个函数应用到集合中的每个元素,并产生一个结果集合,而flatMap跟Map类似,只是传入的函数对每个输入都会返回一个集合(而不是一个元素),然后,flatMap把生成的多个集合“拍扁”成为一个集合。

使用迭代器进行优化,因为迭代器不存数据,可以大大加快效率

package study2.collections

/**
  * @Author: mio
  * @Date: 2019/10/17 15:13
  */
object Main {
  def main(args: Array[String]): Unit = {
    //    使用迭代器优化
    val iterator: Iterator[String] = strings.iterator
    val stringsiterator: Iterator[String] = iterator.flatMap((x: String) => x.split(" "))
    //    stringsiterator.foreach(println)
    val tuples2 = stringsiterator.map((_, 1))
    while (tuples2.hasNext) {
      println(tuples2.next())
    }
  }
}