2017-05-30 121 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 - >根据其他列表排序列表* –