scala中集合的常用方法

本文介绍了Scala集合的各种操作方法,包括最大值最小值(max、min、maxBy、minBy)、过滤(filter、filterNot)、扁平化(flatten)、Euler Diagram(diff、intersect、union)、映射(map)、flatMap、条件检查(forall)、分组(partition)、fold、reduce、aggregate和foreach。通过实例展示了这些方法的用法和效果。
摘要由CSDN通过智能技术生成

注: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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值