在 Java 中,如何根据另一个列表对一个列表进行排序? [英] In Java how do you sort one list based on another?

查看:33
本文介绍了在 Java 中,如何根据另一个列表对一个列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到其他几个与这个问题类似的问题,但我真的找不到任何可以解决我的问题的问题.

I've seen several other questions similiar to this one but I haven't really been able to find anything that resolves my problem.

我的用例是这样的:用户最初有一个项目列表(listA).他们对项目重新排序并希望保留该订单(listB),但是,由于限制,我无法在后端保留订单,因此我必须在检索到 listA 后对其进行排序.

My use case is this: user has a list of items initially (listA). They reorder the items and want to persist that order (listB), however, due to restrictions I'm unable persist the order on the backend so I have to sort listA after I retrieve it.

所以基本上,我有 2 个 ArrayList(listA 和 listB).一个具有列表应该在(listB)中的特定顺序,另一个具有项目列表(listA).我想根据 listB 对 listA 进行排序.

So basically, I have 2 ArrayLists (listA and listB). One with the specific order the lists should be in (listB) and the other has the list of items (listA). I want to sort listA based on listB.

推荐答案

使用 Java 8:

Collections.sort(listToSort, 
    Comparator.comparing(item -> listWithOrder.indexOf(item)));

或更好:

listToSort.sort(Comparator.comparingInt(listWithOrder::indexOf));

这篇关于在 Java 中,如何根据另一个列表对一个列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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