簡體   English   中英

如何將特定的Comparator轉換為Lambda表達式?

[英]How can i convert a specific Comparator to a Lambda expression?

我有一份管理歌曲列表,所以這是我現在對歌曲進行排序的標准。 如何將其“轉換”為lambda表達式?

gestionCancionList.sort(new Comparator<GestionCancion>() {
        @Override
        public int compare(GestionCancion t1, GestionCancion t2){
            return t1.vecesQueSeRepite == t2.vecesQueSeRepite ?
                    t1.song.dameInterprete().compareTo(t2.song.dameInterprete())
                    : (int)(t2.vecesQueSeRepite - t1.vecesQueSeRepite);
        }
    }

更簡單:

Comparator<GestionCancion> aName = (t1,t2) -> t1.vecesQueSeRepite == t2.vecesQueSeRepite ? 
            t1.song.dameInterprete().compareTo(t2.song.dameInterprete())
            : (int)(t2.vecesQueSeRepite - t1.vecesQueSeRepite);

參數類型由比較器的通用類型隱含。

編輯 :可以完成以上操作。 比較器不需要單獨定義。 lambda表達式可以立即傳遞給sort方法。 同樣在這種情況下,收集對象的通用類型隱含了參數的類型。 因此:

gestionCancionList.sort((t1,t2) -> t1.vecesQueSeRepite == t2.vecesQueSeRepite ? 
            t1.song.dameInterprete().compareTo(t2.song.dameInterprete())
            : (int)(t2.vecesQueSeRepite - t1.vecesQueSeRepite));

Comparator工廠方法與方法引用一起使用(如果可能):

Comparator.<GestionCancion, Veces>comparing(gc -> gc.vecesQueSeRepite).reversed()
    .thenComparing(GestionCancion::dameInterprete);

然后編寫代碼:

gestionCancionList.sort(
  Comparator.<GestionCancion, Veces>comparing(gc -> gc.vecesQueSeRepite).reversed()
   .thenComparing(GestionCancion::dameInterprete));

訣竅是應用reversed()保持代碼整潔。

請注意,訪問字段時需要對lambda進行顯式鍵入(您尚未向我們展示vecesQueSeRepite是什么類型;我假設Veces根據需要替換實際類型)。

簡單

Comparator<GestionCancion> aName = (GestionCancion t1, GestionCancion t2)->t1.vecesQueSeRepite == t2.vecesQueSeRepite ?
                t1.song.dameInterprete().compareTo(t2.song.dameInterprete())
                : (int)(t2.vecesQueSeRepite - t1.vecesQueSeRepite);

這里的一個例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM