我有一個扁平的多對象(列表)對象,我想將其轉換爲列表中'key'屬性/字段(例如名稱以下爲)在所有參賽作品中都是獨一無二的。優雅的解決方案,用於過濾列表對於給定的對象屬性是唯一的
在多個條目具有相同的密鑰(名)與最大的creationDate字段中的條目應挑選的情況下。
實施例:
List<Object> myList =
[
{name="abc", age=23, creationDate = 1234L},
{name="abc", age=12, creationDate = 2345L},
{name="ddd", age=99, creationDate = 9999L}
]
應轉換爲:
List<Object> =
[
{name="abc", age=12, creationDate = 2345L},
{name="ddd", age=99, creationDate = 9999L}
]
是否有在Java中來解決這個一種優雅的方式(可能使用番石榴庫?)?我意識到我可以試着用這個名稱爲的HashMap作爲查找所有唯一條目的關鍵,但我感覺有更好的方法來解決這個問題。
謝謝!
太棒了!謝謝!我沒有Java 8可用,但這個解決方案非常簡潔/可讀。我可能會提出一個關於TreeSet副作用的評論,只是選擇了第一個值(我不知道)。 –