我有一个“人”类,其中包含带有3个参数的构造函数。 现在我需要一个排序选项,我需要它按ID,名称或地址的升序和降序进行排序
public class Person
{
private int id;
private String name;
private String addr;
public Person()
{
id = MyTools.getInteger("ID: ");
name = MyTools.getString("Name: ");
addr = MyTools.getString("Address: ");
}
这是我要对其进行排序的地方:
public static void main(String[] args) throws FileNotFoundException
{
boolean loop = true;
System.out.println("Choose:");
System.out.println("\t" + "0 = Exit programm");
System.out.println("\t" + "1 = Add new");
System.out.println("\t" + "2 = Show");
System.out.println("\t" + "3 = Sort");
System.out.println("\t" + "4 = Delete");
System.out.println("\t" + "5 = Save");
System.out.println("\t" + "6 = Help");
TextFile tf = new TextFile("AdressVerwaltung.txt", 'o');
List<Person> adressen = new ArrayList<Person>();
int listSize = 0;
while (loop)
{
int choice = MyTools.getInteger("Please choose which operation you want
to execute (6 = Help): "+"\n");
switch (choice)
{
case 0:
System.out.println("Programmende");
for (int k = 0; k < listSize; k++)
{
tf.printLine(adressen.get(k).toString());
}
tf.close();
loop = false;
break;
case 1:
Person p = new Person();
adressen.add(p);
System.out.println("Data is put in Array!");
listSize = adressen.size();
break;
case 2:
break;
case 3:
break;
现在我希望能够选择是否要按ID,名称或地址进行排序
答案 0 :(得分:1)
您可以使用Java中的Comparator接口创建一些自定义比较器:
例如一个User对象:
public class User {
private final String username;
private final Integer age;
public User(String username, Integer age) {
this.username = username;
this.age = age;
}
public String getUsername() {
return username;
}
public Integer getAge() {
return age;
}
}
按用户名排序的比较器示例:
public class UsernameComparator implements Comparator<User> {
@Override
public int compare(User user, User user2) {
return user.getUsername().compareTo(user2.getUsername());
}
}
并使用:
List<User> users = asList(
new User("Michael", 34),
new User("John", 30),
new User("James", 30),
new User("Mark", 29));
UsernameComparator userNameComparator = new UsernameComparator();
users.sort(userAgeComparator);
或使用Collections.sort(.....):
Collections.sort(users, userAgeComparator);
或者使用Java 8的流API,您可以避免创建新的Comparator类,而只使用流和排序方法:
List sortedList = users.stream()
.sorted(Comparator.comparing(User::getUsername))
.collect(Collectors.toList());
祝你好运:-)