java set集合按年龄顺序排序
对于Java中的Set集合,我们需要先将其转换为List,然后使用Collections.sort()方法进行排序。假设我们有一个存储Person对象的Set集合,Person对象有一个属性为age,表示年龄,我们可以按照以下步骤进行排序:
- 将Set集合转换为List
List
- 使用Collections.sort()方法进行排序
Collections.sort(personList, new Comparator
@Override
public int compare(Person p1, Person p2) {
return p1.getAge() - p2.getAge();
}
});
- 排序完成后,将List转换回Set集合
personSet = new HashSet<>(personList);
完整代码示例:
import java.util.*;
public class SetSortExample {
public static void main(String[] args) {
Set<Person> personSet = new HashSet<>();
personSet.add(new Person("Tom", 20));
personSet.add(new Person("Jerry", 18));
personSet.add(new Person("Mike", 25));
personSet.add(new Person("Lisa", 22));
List<Person> personList = new ArrayList<>(personSet);
Collections.sort(personList, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.getAge() - p2.getAge();
}
});
personSet = new HashSet<>(personList);
System.out.println(personSet);
}
}
class Person { private String name; private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
原文地址: https://www.cveoy.top/t/topic/hgrM 著作权归作者所有。请勿转载和采集!