我已经合并了上面的列表,但需要根据id参数对其进行排序。如何以最简单和最佳的方式做到这一点? 我最初合并了2个用户,现在我想根据其ID对他们进行排序,然后显示结果。有任何想法吗?
import java.io.*;
import java.util.*;
/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
*/
class Employee {
public String name;
public int id;
Employee(String name, int id) {
this.name = name;
this.id = id;
}
public String toString() {
return "<name: " + this.name + ", id: " + this.id + ">";
}
}
class Person {
public String name;
public int id;
Person(String name, int id) {
this.name = name;
this.id = id;
}
public String toString() {
return "<name: " + this.name + ", id: " + this.id + ">";
}
}
public class Solution {
public static void main(String[] args) {
List<Employee> employee = generateEmployees();
List<Person> persons = generatePersons();
ArrayList<Object> merged = new ArrayList<Object>(employee);
merged.addAll(person);
System.out.println("merged:"+merged +"\n");
for(int i=0;i<users.size();i++){
if(person.get(i).id<=5){
System.out.println("UserName:"+person.get(i).name+"\n");
}
}
for(int i=0;i<employee.size();i++){
if(employee.get(i).id<=5){
System.out.println("DesignerName:"+employee.get(i).name+"\n");
}
}
});
}
提前谢谢! 我已经看过几种在线排序方法,但无法使用这是最好的使用方法。只想在排序后显示结果
答案 0 :(得分:3)
User
和Designer
必须从同一类扩展。 (或Designer extand user
)。
然后创建一个比较器(javadoc),然后使用merged.sort (myComparator)
(javadoc)
[ EDIT ]
class MyComparator implements Comparator<User> {
@Override
public int compare(User o1, User o2) {
return Integer.compare(o1.id, o2.id);
}
}
public class User {
public String name;
public int id;
User(String name, int id) {
this.name = name;
this.id = id;
}
public String toString() {
return "<name: " + this.name + ", id: " + this.id + ">";
}
}
public class Designer extends User{
Designer(String enter code herename, int id) {
super(name, id);
}
}
public class Solution {
public static void main(String[] args) {
...
ArrayList<User> merged = new ArrayList<User>(designers);
merged.addAll(users);
merged.sort(new MyComparator());
...
}
}
答案 1 :(得分:0)
假定您有一个名为User
的{{1}}列表:
users