2014-05-11 48 views
0

嗨,我在新階,我不知道如何更改下面的代碼:列表[圖[詮釋,對象]排序

def makeProfil(listProfils: List[Profil]): List[Profil] ={ 

    // var newList = List[Profil] 
      var ll = List[Map[Int,Profil]]() 
    listProfils.foreach(item => { 

    var count = item.czasOgladania.get 
    if(item.czyKupil.get) count = count *4 ; 
    if(item.czyPrzeczytal.get) count = count *3 ; 
    if(item.czyWKarcie.get) count = count *2 ; 
    ll ::= Map (count -> item) 
    }) 

    } 

我想排序LL列表中元素計數從而返回排序列表[Profil]作爲結果。我嘗試了各種各樣的東西,但都沒有效果。

回答

1

List有一個方法,sortWith,它對您的列表進行排序,您可以在其中提供排序列表的條件。條件是一個函數,接受兩個參數(兩個配置文件),結果是布爾值,表明哪一個是「更大」。

所以,你可以做到以下幾點:

ll.sortWith((p1, p2) => 
    getCount(p1) > getCount(p2) 
) 

其中

def getCount(profil: Profil) = { 
    var count = profil.czasOgladania.get 
    if(profil.czyKupil.get) count = count *4 ; 
    if(profil.czyPrzeczytal.get) count = count *3 ; 
    if(profil.czyWKarcie.get) count = count *2 ; 
    count 
} 

更新

順便說一句,似乎profil.czasOgladaniaprofil.czyKupil等等,都是Option秒。在這種情況下,您應該首先檢查它們是否已定義,並執行計算。你可以定義默認值,例如

// if profil.czasOgladania is defined, get the value. Else, return 10. 
val count = profil.czasOgladania.getOrElse(10) 

或:

if(profil.czyWKarcie.getOrElse(false)) count = count *2 
0

您還可以使用sortBy

def makeProfil(listProfils: List[Profil]): List[Profil] = { 
    def getCount(profil: Profil) = { 
    var count = profil.czasOgladania.get 
    if (profil.czyKupil.get) count *= 4 
    if (profil.czyPrzeczytal.get) count *= 3 
    if (profil.czyWKarcie.get) count *= 2 
    count 
    } 

    listProfils.sortBy(p => getCount(p)) 
} 
1

這裏是沒有任何可變狀態整件事商(VAR是不好的做法)。首先,將配置文件列表映射到(計數,配置文件)元組列表。地圖似乎不是必要的。然後,按照元組中的第一項對列表進行排序,然後將其映射到配置文件列表(元組中的第二項)。

def makeProfil(listProfils: List[Profil]): List[Profil] ={ 

    val profileCounts = listProfils.map(item => { 
     val count = item.czasOgladania.getOrElse(0) 
     val kupil = if(item.czyKupil.isDefined) 4 else 1 
     val przeczytal = if(item.czyPrzeczytal.isDefined) 3 else 1; 
     val wKarcie = if(item.czyWKarcie.isDefined) 2 else 1 ; 
     val finalCount = count * kupil * przeczytal * wKarcie 
     (count, item) 
    }) 
    profileCounts.sortBy(_._1).map(_._2) 
}