注:val map = Map((“b”,2),(“a”,1),(“d”,4)),这里调用的方法是使用map调用的
1. 最大值最小值
方法:max、min、maxBy、minBy
def minBy[B](f: A => B)(implicit cmp: Ordering[B]): A = {
if (isEmpty)
throw new UnsupportedOperationException("empty.minBy")
reduceLeft((x, y) => if (cmp.lteq(f(x), f(y))) x else y)
}
case class Book(title: String, pages: Int)
val books = Seq( Book("Future of Scala developers", 85),
Book("Parallel algorithms", 240),
Book("Object Oriented Programming", 130),
Book("Mobile Development", 495) )
//Book(Mobile Development,495)
books.maxBy(book => book.pages)
//Book(Future of Scala developers,85)
books.minBy(book => book.pages)
如上所示,minBy & maxBy 方法解决了复杂数据的问题。你只需选择决定数据最大或最小的属性。
2.过滤
方法:filter、filterNot
/** Selects all elements of this $coll which satisfy a predicate.
*
* @param p the predicate used to test elements.
* @return a new $coll consisting of all elements of this $coll that satisfy the given
* predicate `p`. The order of the elements is preserved.
*/
def filter(p: A => Boolean): Repr = {
val b = newBuilder
for (x <- this)
if (p(x)) b += x
b.result
}
3.Flatten
方法:flatten
flatten可以把嵌套的结构展开.
/** Converts this $coll of traversable collections into
* a $coll formed by the elements of these traversable
* collections.
*
* @tparam B the type of the elements of each traversable collection.
* @param asTraversable an implicit conversion which asserts that the element
* type of this $coll is a `GenTraversable`.
* @return a new $coll resulting from concatenating all element ${coll}s.
*
* @usecase def flatten[B]: $Coll[B]
*
* @inheritdoc
*
* The resulting collection's type will be guided by the