This question already has answers here:
In Java how do you sort one list based on another?
                                
                                    (20个答案)
                                
                        
                去年关闭。
            
        

我有一个对象列表,需要根据特定顺序对其进行排序。类似于以下代码:

preOrderedList = {"bmw","audi","benz"};


来自UI的列表是carList {"audi","benz","bmw"}

这里的问题是用户将能够从应用程序添加新行。假设用户添加新行“ audi”,那么carList将类似于
 {"audi","benz","bmw","audi"}。在这种情况下,列表应按{"bmw","audi","audi","benz"}.排序

我试过下面的代码。它仅适用于不添加新行的情况,即{"audi","benz","bmw"}

同样,它在排序时也只会更改name(“ bmw”,“ audi”,“ benz”)位置。我在汽车课上还有一个字段是数量。数量将保持不变。该位置也应随名称一起更改。

final List<String> preOrderedList = Arrays.asList("bmw","audi","benz");

Collections.sort(carList, new Comparator<Car>() {
        public int compare(Car l1, Car l2) {
            if (preOrderedList.contains(l1.getName().trim()) && preOrderedList.contains(l2.getName().trim())) {
                return preOrderedList.indexOf(l1.getName().trim()) - preOrderedList.indexOf(l2.getName().trim());
            }
            if (preOrderedList.contains(l1.getName().trim())) {
                return -1;
            }
            if (preOrderedList.contains(l2.getName().trim())) {
                return 1;
            }
            return l1.getName().trim().toString().compareTo(l2.getName().trim().toString());
        }
    });


我期望输出为{"bmw","audi","audi","benz"},但我的实际输出为{"bmw","audi","benz","audi"}.

最佳答案

这可以用guavaOrdering.explicit优雅地解决:

Collections.sort(carList, Ordering.explicit(preOrderedList).onResultOf(new Function<Car, String>() {
    @Override
    public String apply(Car car) {
        return car.getName();
    }
}));


Guava thas支持Java 6的最新版本是Guava 20.0:

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>20.0</version>
</dependency>

07-28 13:07
查看更多