我有两个java.util.List,例如看起来像这样:
List<MyObject> myObjects = ...
MyObject myObject1 = ...
MyObject myObject2 = ...
MyObject myObject3 = ...
MyObject myObject4 = ...
MyObject myObject5 = ...
myObjects.add(myObjet1);
...
,第二个List看起来像这样:
List<MyObject> otherListObjects = ...
MyObject myObject1 = ...
MyObject myObject5 = ...
现在我的目标是列出一个列表,其中 myObject1 和 myObject5 位于前两个位置,而不是其他位置。 在Java 8中是否有简单的可能性?
答案 0 :(得分:6)
您可以根据myObjects
中显示的索引对myOtherObjects
项进行排序:
myObjects.sort(Comparator.comparingInt(s -> {
int ind = myOtherObjects.indexOf(s);
if (ind >= 0) {
return ind;
}
return Integer.MAX_VALUE;
}));
Malte Hartwig提出了一个很酷的变种。它利用Java的整数算术下溢,因此如果在myOtherObjects
中找不到该对象,则将-1
添加到Integer.MIN_VALUE
将下溢并生成2147483647
:
myObjects.sort(
Comparator.comparingInt(s -> myOtherObjects.indexOf(s) + Integer.MIN_VALUE));
如果您不关心myOtherObjects
内的内部订单,可以大大简化:
myObjects.sort(Comparator.comparing(myOtherObjects::contains).reversed());
答案 1 :(得分:2)
我不确定在阅读您的问题时,您是否需要排序的第一个列表或新列表。以下是创建新列表的两种方法(用于对现有列表进行排序,请查看Mureinik的答案)。
如果您坚持使用Java 8,请尝试使用Streams:
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);
}