2017-05-30 38 views
1

我確實有兩個java.util.List,例如看起來是這樣的:Java 8 - >根據其他列表排序列表

List<MyObject> myObjects = ... 
MyObject myObject1 = ... 
MyObject myObject2 = ... 
MyObject myObject3 = ... 
MyObject myObject4 = ... 
MyObject myObject5 = ... 
myObjects.add(myObjet1); 
... 

和第二列表如下:

List<MyObject> otherListObjects = ... 
MyObject myObject1 = ... 
MyObject myObject5 = ... 

現在我的目標是有一個列表,其中myObject1myObject5處於前兩位並超過其他。 Java 8中有這樣簡單的可能性嗎?

+3

爲什麼有一個原因,你需要的Java 8?你指的是哪個功能?這很容易通過創建一個新列表完成,調用'newList.addAll(otherListObjects); myObjects.removeAll(otherListObjects(); newList.addAll(myObjects);' –

+1

編寫一個比較器,用於獲取otherList中wo比較對象的索引,如果未找到則比較Integer.MAX_VALUE,然後比較這兩個整數值 –

+1

so' otherListObjects'在新列表中定義了「n-first」元素?如果這樣做,這些對象是否會覆蓋hashcode/equals? – Eugene

回答

6

你可以根據它們出現在myOtherObjects指數myObjects的項目進行排序:

myObjects.sort(Comparator.comparingInt(s -> { 
    int ind = myOtherObjects.indexOf(s); 
    if (ind >= 0) { 
     return ind; 
    } 
    return Integer.MAX_VALUE; 
})); 

在這清涼的變異是由馬爾特哈特維希建議。它利用Java的整數運算下溢,因此,如果對象未在myOtherObjects發現,加入-1Integer.MIN_VALUE下溢,併產生2147483647

myObjects.sort(
    Comparator.comparingInt(s -> myOtherObjects.indexOf(s) + Integer.MIN_VALUE)); 

如果你不關心內部秩序內myOtherObjects,這可以大大簡化:

myObjects.sort(Comparator.comparing(myOtherObjects::contains).reversed()); 
+1

對於那些認爲'+ Integer.MIN_VALUE'看起來「太神奇」的用戶,可以選擇使用' Comparator.comparingLong(s - > Integer.toUnsignedLong(myOtherObjects.indexOf(s)))'語義上,它是一樣的;另見['Integer.compareUnsigned(...)'](http://grepcode.com/file /repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/lang/Integer.java#Integer.compareUnsigned%28int%2Cint%29)... – Holger

2

我不知道從看你的問題,無論你是需要排序的第一個列表還是新的列表。以下是創建新列表的兩種方法(用於對現有列表進行排序,查看Mureinik的答案)。

如果你堅持的Java 8,嘗試流:

Stream.of(otherListObjects, myObjects) 
     .flatMap(Collecttion::stream) 
     .distinct 
     .collect(Collectors.toList()); 

這是很簡單的用老式的Java來做到這一點,雖然:

List<MyObject> newList = new ArrayList<>(); 
newList.addAll(otherListObjects); 
for (MyObject o : myObjects) { 
    if (!newList.contains(o)) 
     newList.add(o); 
} 
+2

這並不排序第一個列表,該連接第二個與第一個。 –

+0

@JBNizet操作說他們想要t他第一個列表排序?我讀了幾次。 –

+2

就在那裏,在標題中:* Java 8 - >根據其他列表排序列表* –