在Java中,对名字进行排序可以通过以下几种方式实现:
1. 使用`Collections.sort`函数对实现了`Comparable`接口的对象集合进行排序。
2. 使用`Arrays.sort`函数对数组进行排序,并通过`Comparator`实现自定义排序规则。
3. 对于中文名字排序,可以使用`Collator`类,它可以根据语言环境对字符串进行排序。
4. 如果需要先按名称排序,然后按日期排序,可以创建一个自定义的比较器`Comparator`。
下面是一些示例代码,展示如何实现这些排序方法:
示例1:使用`Collections.sort`和`Comparable`接口
import java.util.*;
class Person implements Comparable
{ String name;
public Person(String name) { this.name = name; }
@Override
public int compareTo(Person other) {
return this.name.compareTo(other.name);
}
}
public class NameSort {
public static void main(String[] args) {
List
people = new ArrayList<>(); people.add(new Person("Alice"));
people.add(new Person("Bob"));
people.add(new Person("Charlie"));
Collections.sort(people);
for (Person person : people) {
System.out.println(person.name);
}
}
}
示例2:使用`Arrays.sort`和`Comparator`
import java.util.*;
class Person {
String name;
public Person(String name) { this.name = name; }
}
public class NameSort {
public static void main(String[] args) {
Person[] people = {
new Person("Alice"),
new Person("Bob"),
new Person("Charlie")
};
Arrays.sort(people, new Comparator
() { @Override
public int compare(Person p1, Person p2) {
return p1.name.compareTo(p2.name);
}
});
for (Person person : people) {
System.out.println(person.name);
}
}
}
示例3:中文名字排序
import java.util.*;
import java.text.*;
public class SortByChinese {
public static void main(String[] args) {
String[] names = {"张三", "李四", "刘翔", "刘六", "郭晶晶", "姚明"};
getSortOfChinese(names);
for (String name : names) {
System.out.println(name);
}
}
public static String[] getSortOfChinese(String[] names) {
Collator cmp = Collator.getInstance(Locale.CHINA);
Arrays.sort(names, cmp);
return names;
}
}
示例4:先按名称排序,然后按年龄排序
import java.util.*;
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return name + " " + age;
}
}
public class NameAgeSort {
public static void main(String[] args) {
List
people = Arrays.asList( new Person("tarun", 28),
new Person("arun", 29),
new Person("varun", 12),
new Person("arun", 22)
);
Collections.sort(people, new Comparator
() { @Override
public int compare(Person p1, Person p2) {
int nameComparison = p1.name.compareTo(p2.name);
if (nameComparison != 0) {
return nameComparison;
} else {
return Integer.compare(p1.age, p2.age);
}
}
});
for (Person person : people) {
System.out.println(person);
}
}
}
示例5:先按名称排序,然后按日期排序
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/145111.html