@MiloXia
2015-09-09T10:15:24.000000Z
字数 1311
阅读 1872
scala
val map = Map("w1" -> Set("w1"),
"w2" -> Set("w2", "b4"),
"w3" -> Set("w3", "b5"),
"b4" -> Set("b4", "w2"),
"b5" -> Set("b5", "w3"))
val list = map.toList
println(list)
def mapGroup[K, V, L[_]](list: List[(K, L[V])]): List[L[V]] = list match {
case List() => Nil
case head :: rest =>
head._2 :: mapGroup(rest.filter{ case (k, v) =>
v != head._2
})
}
println(mapGroup(list))
哈哈,逗比了吧!更简洁的方法:
def mapGroup2[K, V, L[_]](map: Map[K, L[V]]): List[L[V]] = map.values.toList.distinct
println(mapGroup2(map))
哈哈,又是我; 但是,第一个方法稍微改造一下可以保留group之后的keys
def mapGroup3[K, V, L[_]](list: List[(K, L[V])]): (List[List[K]], List[L[V]]) = list match {
case List() => (Nil, Nil)
case head :: rest =>
val (ks, vs) = mapGroup3(rest.filter{ case (k, v) =>
v != head._2
})
((head._1 :: rest.filter{ case (k, v) =>
v == head._2
}.map(_._1)) :: ks,
head._2 :: vs)
}
result
List((w2,Set(w2, b4)), (b4,Set(b4, w2)), (w1,Set(w1)), (b5,Set(b5, w3)), (w3,Set(w3, b5)))
List(Set(w2, b4), Set(w1), Set(b5, w3))
List(Set(w2, b4), Set(w1), Set(b5, w3))
(List(List(w2, b4), List(w1), List(b5, w3)),List(Set(w2, b4), Set(w1), Set(b5, w3)))
class SpinLock {
import java.util.concurrent.atomic.AtomicReference
private val sign : AtomicReference[Thread] = new AtomicReference
def lock {
val current = Thread.currentThread
while(!sign.compareAndSet(null, current)){
}
}
def unlock {
val current = Thread.currentThread
sign.compareAndSet(current, null)
}
}
//使用
spinLock.lock
try {
//...
} finally {
spinLock.unlock
}