Java 8 - >排序列表取决于其他列表

时间:2017-05-30 18:56:35

标签: java sorting java-8

我有两个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中是否有简单的可能性?

2 个答案:

答案 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);
}
相关问题