Scala访问排序集的元素



我有一个SortedSet[Int]对象,我希望能够通过检索mySet(sizeOfMySet/2)来找到它的中值,但它只显示true和false之类的内容。是否有其他方法可以检索元素?

scala> val sorted = collection.immutable.SortedSet(5,3,1,7,2)
sorted: scala.collection.immutable.SortedSet[Int] = TreeSet(1, 2, 3, 5, 7)
scala> val half = sorted.size / 2
half: Int = 2
scala> val median = sorted.slice(half, half+1).headOption
median: Option[Int] = Some(3)

如果你确定集合是非空的(因此不需要Option来覆盖这种情况),你可以只使用head

以下是如何获得对象集合的中值的方法。

val sorted = collection.immutable.SortedSet(5,3,1,2,4,6)
val size = sorted.size
val median = if(size%2==0){
 // if there is a pair number of items, 
 // the median is the average of the two central elements
 (sorted.take(size/2+1).range(size/2, size/2+2).sum)/2.0
}
else{
 sorted.take(size/2+1).last
}

最新更新