当前位置: 首页>>代码示例>>Scala>>正文


Scala ArrayBuffer类代码示例

本文整理汇总了Scala中collection.mutable.ArrayBuffer的典型用法代码示例。如果您正苦于以下问题:Scala ArrayBuffer类的具体用法?Scala ArrayBuffer怎么用?Scala ArrayBuffer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了ArrayBuffer类的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: ExTwo

//设置package包名称以及导入依赖的类
package com.utad.bigdatascala

object ExTwo extends App {

  val minAge = 18

  // Let's generate a bunch of 10 persons, some of then sharing age
  val people = (1 to 10) map { n =>
    Person(s"Person$n", minAge + n % 3, s"[email protected]")
  } toList

  { //Non functional approach: Creating an empty map and updating it
    import collection.mutable.{Map, ArrayBuffer}

    val resMap: Map[Int, ArrayBuffer[Person]] = Map.empty

    people foreach { case person @ Person(_, age, _) =>
      if(resMap contains age)
        resMap(age) += person
      else
        resMap += (age -> ArrayBuffer(person))
    }

    println(resMap)

  }

  { //Functional approach: Creating a map using higher order methods
    val resMap: Map[Int, List[Person]] =
      people.foldRight(Map.empty[Int, List[Person]]) {
        case (person @ Person(_, age, _), prevMap) =>
          val newOrUpdatedEntry = prevMap.get(age) map { prevList => // If the age was already in the map,..
            person +: prevList //then we have to provide an updated list.
          } getOrElse Nil //otherwise, an empty list.
          prevMap + (age -> newOrUpdatedEntry)
      }

    println(resMap)

  }

} 
开发者ID:pfcoperez,项目名称:utad_bigdata_introscala,代码行数:43,代码来源:ExTwo.scala

示例2: RNA

//设置package包名称以及导入依赖的类
package rna

import collection.IndexedSeqLike
import collection.mutable.{ArrayBuffer, Builder}
import collection.generic.CanBuildFrom

final class RNA private (val groups: Array[Int], val length: Int)
  extends IndexedSeq[Base] with IndexedSeqLike[Base, RNA]
{
  import RNA._

  def apply(i: Int): Base = {
    require(i >= 0 && i < length)
    Base.fromInt(groups(i / N) >> (i % N * S) & M)
  }

  override protected[this] def newBuilder: Builder[Base, RNA] = RNA.newBuilder

  // more efficient foreach implementation
  override def foreach[U](f: (Base) => U): Unit = {
    var i = 0
    var b = 0
    while (i < length) {
      b = if (i % N == 0) groups(i / N) else b >>> S
      f(Base.fromInt(b & M))
      i += 1
    }
  }
}

object RNA {
  // number of bits necessary to represent group
  private val S = 2

  // number of groups that fit in an Int
  private val N = 32 / S

  // bitmask to isolate a group
  private val M = (1 << S) - 1

  def fromSeq(buf: Seq[Base]): RNA = {
    val groups = new Array[Int]((buf.length + N - 1) / N)
    for (i <- buf.indices) groups(i / N) |= Base.toInt(buf(i)) << (i % N * S)
    new RNA(groups, buf.length)
  }

  def apply(bases: Base*) = fromSeq(bases)

  def newBuilder: Builder[Base, RNA] = new ArrayBuffer mapResult fromSeq

  implicit def canBuildFrom: CanBuildFrom[RNA, Base, RNA] = new CanBuildFrom[RNA, Base, RNA] {
    def apply(): Builder[Base, RNA] = newBuilder
    def apply(from: RNA): Builder[Base, RNA] = newBuilder
  }
} 
开发者ID:mhotchen,项目名称:programming-in-scala,代码行数:56,代码来源:RNA.scala

示例3: PerformanceTimer

//设置package包名称以及导入依赖的类
package ppl.delite.benchmarking.sorting.tpch.util

import collection.mutable.{ArrayBuffer, HashMap}

object PerformanceTimer
{
  val currentTimer = new HashMap[String, Long]
  val times = new HashMap[String, ArrayBuffer[Double]]

  def start(component: String, printMessage: Boolean = true) {
    if (!times.contains(component)) {
      times += component -> new ArrayBuffer[Double]()
    }
    if (printMessage) println("[METRICS]: Timing " + component + " #" + times(component).size + " started")
    currentTimer += component -> System.currentTimeMillis
  }

  def stop(component: String, printMessage: Boolean = true) {
    val x = (System.currentTimeMillis - currentTimer(component)) / 1000D
    times(component) += x
    if (printMessage) println("[METRICS]: Timing " + component + " #" + (times(component).size - 1) + " stopped")
  }

  def totalTime(component: String) {
    val total = times(component).toList.reduceLeft[Double](_+_)
    println("[METRICS]: total time for component " + component + ": " + total)
  }

  def clearAll() {
    for((k,v) <- times) {
      v.clear
    }
  }

  def print(component: String) {
    val timeStr = times.get(component) map { "[METRICS]: Latest time for component " + component + ": " +  _.last.formatted("%.6f") + "s" }
    println(timeStr getOrElse "[METRICS]: No data for component " + component)
  }

} 
开发者ID:leratojeffrey,项目名称:OptiSDR-Compiler,代码行数:41,代码来源:PerformanceTimer.scala

示例4: addSync

//设置package包名称以及导入依赖的类
package ppl.delite.runtime.codegen.sync

import ppl.delite.runtime.graph.ops._
import collection.mutable.{HashSet, ArrayBuffer}
import ppl.delite.runtime.codegen.{ScalaExecutableGenerator, ExecutableGenerator}
import ppl.delite.runtime.scheduler.OpList

/*
 * Pervasive Parallelism Laboratory (PPL)
 * Stanford University
 *
 */

trait SyncGenerator {

  def addSync(s: Sync) = s match {
    case s:SendData => sendData(s)
    case s:ReceiveData => receiveData(s)
    case s:SendView => sendView(s)
    case s:ReceiveView => receiveView(s)
    case s:Notify => sendSignal(s)
    case s:Await => awaitSignal(s)
    case s:SendUpdate => sendUpdate(s)
    case s:ReceiveUpdate => receiveUpdate(s)
    case _ => throw new IllegalArgumentException("Unrecognized Sync type: " + s)
  }

  protected def sendData(s: SendData) { } //TODO: should probably throw an exception
  protected def receiveData(s: ReceiveData) { notImplemented(s) }
  protected def sendView(s: SendView) { }
  protected def receiveView(s: ReceiveView) { notImplemented(s) }
  protected def sendSignal(s: Notify) { }
  protected def awaitSignal(s: Await) { notImplemented(s) }
  protected def sendUpdate(s: SendUpdate) { }
  protected def receiveUpdate(s: ReceiveUpdate) { }

  private def notImplemented(s: Sync) = sys.error("don't know how to synchronize " + s)

  protected def getOpSync(op: DeliteOP) = getSync(op, "op_"+op.id)
  protected def getSync(op: DeliteOP, name: String): String = { "Result_"+op.id+"_"+name }

  protected def mangledName(name: String) = name.replaceAll("\\s","").map(c => if(!c.isDigit && !c.isLetter) '_' else c) 
}

trait SyncObjectGenerator extends SyncGenerator with ExecutableGenerator {

  protected val sync: ArrayBuffer[Send]

  def executableNamePrefix = "Sync_"

  protected def addSyncObject(): Unit

  def makeSyncObjects {
    writeHeader()
    addSyncObject()
    writeFooter()
    addSource(out.toString)
  }
} 
开发者ID:leratojeffrey,项目名称:OptiSDR-Compiler,代码行数:60,代码来源:SyncGenerator.scala

示例5: AliasTable

//设置package包名称以及导入依赖的类
package ppl.delite.runtime.codegen

import collection.mutable.ArrayBuffer

final class AliasTable[T] {

  private val table = new ArrayBuffer[Set[T]]

  private[codegen] def get(name: T): Set[T] = {
    val sets = table.filter(s => s.contains(name))
    assert(sets.length < 2)
    if (sets.length == 0) Set(name)
    else sets(0)
  }

  private[codegen] def add(name1: T, name2: T) {
    val sets = table.filter(s => s.contains(name1) || s.contains(name2))
    assert(sets.length < 3)
    if (sets.length == 0) {
      table += Set(name1,name2)
    }
    else {
      val newSet = sets.reduceLeft(_ union _)
      for (s <- sets) table -= s
      table += newSet
    }
  }

  private[codegen] def remove(name: T) {
    val sets = table.filter(s => s.contains(name))
    assert(sets.length == 1)
    table -= sets(0)
    table += (sets(0)-name)
  }

  private[codegen] def clear {
    table.clear
  }

} 
开发者ID:leratojeffrey,项目名称:OptiSDR-Compiler,代码行数:41,代码来源:AliasTable.scala

示例6: decr

//设置package包名称以及导入依赖的类
package com.twitter.finagle.util

import collection.mutable.ArrayBuffer


  def decr() = {
    val pendingTasks = synchronized {
      require(count > 0)
      count -= 1
      if (count == 0) {
        val pending = waiters
        waiters = new ArrayBuffer[() => Unit]
        Left(pending)
      } else {
        Right(count)
      }
    }

    pendingTasks match {
      case Left(tasks) =>
        tasks foreach { _() }; 0
      case Right(count) =>
        count
    }
  }

  def getCount = count
} 
开发者ID:deenar,项目名称:fintest,代码行数:29,代码来源:AsyncLatch.scala

示例7: MockTimer

//设置package包名称以及导入依赖的类
package com.twitter.finagle

import collection.mutable.ArrayBuffer

import com.twitter.util.{Time, Duration}

class MockTimer extends com.twitter.util.Timer {
  case class Task(var when: Time, runner: Function0[Unit])
    extends com.twitter.util.TimerTask
  {
    var isCancelled = false
    def cancel() { isCancelled = true; when = Time.now; tick() }
  }

  var isStopped = false
  var tasks = ArrayBuffer[Task]()

  def tick() {
    if (isStopped)
      throw new Exception("timer is stopped already")

    val now = Time.now
    val (toRun, toQueue) = tasks.partition { task => task.when <= now }
    tasks = toQueue
    toRun filter { !_.isCancelled } foreach { _.runner() }
  }

  def schedule(when: Time)(f: => Unit) = {
    val task = Task(when, () => f)
    tasks += task
    task
  }

  def schedule(when: Time, period: Duration)(f: => Unit) =
    throw new Exception("periodic scheduling not supported")

  def stop() { isStopped = true }
} 
开发者ID:deenar,项目名称:fintest,代码行数:39,代码来源:Timer.scala


注:本文中的collection.mutable.ArrayBuffer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。