[关闭]
@MiloXia 2015-09-09T10:15:24.000000Z 字数 1311 阅读 1872

scala code

scala


对map的value做group操作

  1. val map = Map("w1" -> Set("w1"),
  2. "w2" -> Set("w2", "b4"),
  3. "w3" -> Set("w3", "b5"),
  4. "b4" -> Set("b4", "w2"),
  5. "b5" -> Set("b5", "w3"))
  6. val list = map.toList
  7. println(list)
  8. def mapGroup[K, V, L[_]](list: List[(K, L[V])]): List[L[V]] = list match {
  9. case List() => Nil
  10. case head :: rest =>
  11. head._2 :: mapGroup(rest.filter{ case (k, v) =>
  12. v != head._2
  13. })
  14. }
  15. println(mapGroup(list))

哈哈,逗比了吧!更简洁的方法:

  1. def mapGroup2[K, V, L[_]](map: Map[K, L[V]]): List[L[V]] = map.values.toList.distinct
  2. println(mapGroup2(map))

哈哈,又是我; 但是,第一个方法稍微改造一下可以保留group之后的keys

  1. def mapGroup3[K, V, L[_]](list: List[(K, L[V])]): (List[List[K]], List[L[V]]) = list match {
  2. case List() => (Nil, Nil)
  3. case head :: rest =>
  4. val (ks, vs) = mapGroup3(rest.filter{ case (k, v) =>
  5. v != head._2
  6. })
  7. ((head._1 :: rest.filter{ case (k, v) =>
  8. v == head._2
  9. }.map(_._1)) :: ks,
  10. head._2 :: vs)
  11. }

result

  1. List((w2,Set(w2, b4)), (b4,Set(b4, w2)), (w1,Set(w1)), (b5,Set(b5, w3)), (w3,Set(w3, b5)))
  2. List(Set(w2, b4), Set(w1), Set(b5, w3))
  3. List(Set(w2, b4), Set(w1), Set(b5, w3))
  4. (List(List(w2, b4), List(w1), List(b5, w3)),List(Set(w2, b4), Set(w1), Set(b5, w3)))

自旋锁

  1. class SpinLock {
  2. import java.util.concurrent.atomic.AtomicReference
  3. private val sign : AtomicReference[Thread] = new AtomicReference
  4. def lock {
  5. val current = Thread.currentThread
  6. while(!sign.compareAndSet(null, current)){
  7. }
  8. }
  9. def unlock {
  10. val current = Thread.currentThread
  11. sign.compareAndSet(current, null)
  12. }
  13. }
  14. //使用
  15. spinLock.lock
  16. try {
  17. //...
  18. } finally {
  19. spinLock.unlock
  20. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注