我需要对Person对象的列表进行排序(List<Person>,其中每个Person对象几乎没有像id(唯一)、name、age…这样的属性。等)。
排序顺序基于另一个列表。该列表包含一组Person id(已经排序的List<String> )。
按照与使用Kotlin或List<Person>的id列表相同的顺序排序id的最佳方法是什么。
示例:
List Person {
(“ID1”,”PERSON1”,22,..), (“ID-2”,”PERSON2”,20,..) ), (“ID-3”,”PERSON3”,19,..),…..
}已订购的Id列表:
List of ID {(“ID2”), (“ID1”),(”ID3”)….}排序的Person列表应该是:
List PERSON {
(“ID-2”,”PERSON 2”,20,..) ), (“ID1”,”PERSON 2”,22,..), (“ID-3”,”PERSON 2”,19,..),…..
}如果Person列表包含在id列表中没有提到的任何id,那么这些值应该位于排序列表的末尾。
编辑:这是我目前使用Java的方式。我希望有一个比这更好的方法:
public static List<Person> getSortList(List <Person> unsortedList, List<String> orderList){
if(unsortedList!=null && !unsortedList.isEmpty() && orderList!=null && !orderList.isEmpty()){
List sortedList = new ArrayList<OpenHABWidget>();
for(String id : orderList){
Person found= getPersonIfFound(unsortedList, id); // search for the item on the list by ID
if(found!=null)sortedList.add(found); // if found add to sorted list
unsortedList.remove(found); // remove added item
}
sortedList.addAll(unsortedList); // append the reaming items on the unsorted list to new sorted list
return sortedList;
}
else{
return unsortedList;
}
}
public static Person getPersonIfFound(List <Person> list, String key){
for(Person person : list){
if(person.getId().equals(key)){
return person;
}
}
return null;
}发布于 2017-07-27 11:39:13
一个有效的解决方案是首先创建从ids中的ID (所需的ID顺序)到该列表中的索引的映射:
val orderById = ids.withIndex().associate { (index, it) -> it.id to index }然后按照映射中people的id顺序对列表进行排序:
val sortedPeople = people.sortedBy { orderById[it.id] }注意:如果一个人的ID不存在于ids中,他们将被放在列表的第一位。要将它们放在最后,可以使用nullsLast比较器:
val sortedPeople = people.sortedWith(compareBy(nullsLast<String>()) { orderById[it.id] })发布于 2017-07-27 11:25:37
我会做类似的事情(用伪代码,因为我不知道你的代码是什么样子)。
listOfPersons = [{2,Bob},{3,Claire},{1,Alice}]
orderList = [1,3,2]
sortedList = []
for(id in orderList)
person = listOfPersons.lookup(id)
sortedList.add(person) 如果您有一个地图(id-> person)而不是listOfPersons,那么查找就更容易了。
发布于 2017-07-27 12:15:00
试试下面的代码。
Map<String, Person> personMap=new HashMap<>(); // create a map with key as ID and value as Person object
List<String> orderList=new ArrayList<>(); // create a list or array with ID order
List<Person> outputList=new ArrayList<>(); //list to hold sorted values
//logic
// to sort Person based on ID list order
for (String order : orderList) {
if(personMap.containsKey(order)){
outputList.add(personMap.get(order));
personMap.remove(order);
}
}
// logic to add the Person object whose id is not present in ID order list
for (Entry<String, Person> entry : personMap.entrySet())
{
int lastIndex=outputList.size();
outputList.add(lastIndex, entry.getValue());
lastIndex++;
}现在,outputList将具有您期望的值.
https://stackoverflow.com/questions/45349293
复制相似问题