如何使用Map键作为列表对象和值作为顺序对ArrayList进行排序? [英] How to sort an ArrayList using a Map key as list object and value as the order?
问题描述
我需要保持对象列表的顺序,因为可以在我的Web应用程序中随时对其进行更改和重新排序.
I need to keep the order of my list of objects as it can be changed and reordered anytime in my webapp.
在我的模型中,我有一个对象示例的数组列表
In my model I have a array list of objects example
objectList = [object1, object2, object3, object4]
,然后将属于该实例的每个对象的顺序保存到一个Map示例中:订购
and I save the order of each object belonging to this instance to a Map example: order
{
"object1":4,
"object2":2,
"object3":1,
"object4":3
}
因此,我想根据对象ID作为键检索的映射中的值对数组进行排序:
Therefore i want to sort my array according to its value in the map retrieved by the objects Id as the key:
预期结果:
[object3, object2, object4, object1]
我将如何去做?
推荐答案
Assuming your objects have a getter for the id getId()
, then you can make use of the Comparator.comparing()
helper method, which creates a comparator for the provided lambda:
objectList.sort(Comparator.comparing(o -> yourMap.get(o.getId()));
这实际上与编写自己的 Comparator
或编写自己的compare方法相同.
This effectively the same as writing your own Comparator
or writing your own compare method.
这篇关于如何使用Map键作为列表对象和值作为顺序对ArrayList进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!