如何使用Map键作为列表对象和值作为顺序对ArrayList进行排序? [英] How to sort an ArrayList using a Map key as list object and value as the order?

查看:52
本文介绍了如何使用Map键作为列表对象和值作为顺序对ArrayList进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要保持对象列表的顺序,因为可以在我的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]

我将如何去做?

推荐答案

假设您的对象具有ID getId()的吸气剂,则可以使用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆