English 中文(简体)
列出物体清单,注明物体清单[封闭]
原标题:Sorting a list of objects with the order of an List of object-Ids [closed]
Closed. This question needs details or clarity. It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post.

Closed 9 years ago.

这是我拥有的:

class Person {
  Integer id;
  String name;
}

// A list of persons:
List<Person> persons

// Now I have something like this:
List<Integer> ids  // where the ids are stored in an specific order

Basically I wanna sort the persons list in the same order like the ids.

难道有更好的方式使用像两种假肢,并创造新的个人-文化?

regards && tia

页: 1

最佳回答

http://www.un.org。 参比者获得被比较者的遗嘱,并在子女名单中按顺序排列:

List<Person> persons = ...;
final List<Integer> ids = ...;

Collections.sort(persons, new Comparator<Person>() {
    @Override
    public int compare(Person p1, Person p2) {
        int index1 = ids.indexOf(p1.getId());
        int index2 = ids.indexOf(p2.getId());
        return index1 < index2 ? -1 : (index1 == index2 ? 0 : 1);
    }
});

Note: this code assumes that the ids of all persons in the list will appear in the ids list.

问题回答
  1. Map each of the ids into its index: Map<Integer, Integer> idToIndex;
  2. Run the following loop.

for (int i = 0, size = persons.length - 1; i < size; ++i) {
  var targetIndex = idToIndex.get(persons.get(i).id);
  if (targetIndex != i) {
    persons[i] <-> persons[targetIndex];
  }
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签