在Java的世界里排序有很多方法,今天我就介绍一下TreeSet和Comparator进行排序排序的方法。
一、利用TreeSet和Comparator进行数字的升序和降序排序- package edu.sdp.demo;
- import java.util.Comparator;
- import java.util.Iterator;
- import java.util.TreeSet;
- public class TreeSetComparator {
-
- public static void main(String[] args) {
-
- // 利用TreeSet和Comparator 进行排序
- Comparator<Object> com = new Comparator<Object>() {
- @Override
- public int compare(Object o1, Object o2) {
- // TODO Auto-generated method stub
- Integer oo1 = (Integer) o1;
- Integer oo2 = (Integer) o2;
- /*
- * 降序排列
-
- if (oo1 > oo2) {
- return -1;
- }else if(oo1 < oo2){
- return 1;
- }else{
- return 0;
- }
- */
-
- /*
- * 升序排列
- */
- if (oo1 > oo2) {
- return 1;
- } else if(oo1 <oo2){
- return -1;
- }else{
- return 0;
- }
- }
-
- };
-
- TreeSet tree = new TreeSet(com);
-
- tree.add(1);
- tree.add(5);
- tree.add(100);
- tree.add(30);
- tree.add(20);
- Iterator iter = tree.iterator();//迭代器
- while (iter.hasNext()) {
- System.out.println(iter.next());
- }
- }
- }
复制代码 二、利用TreeSet和Comparator进行方法的排序
1、Person类- package edu.sdp.java.demo;
- public class Person {
- private int id;
- private String name;
- private int age;
- private String address;
-
- public Person(){
-
- }
-
-
-
- public Person(int id, String name, int age, String address) {
- super();
- this.id = id;
- this.name = name;
- this.age = age;
- this.address = address;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getAddress() {
- return address;
- }
- public void setAddress(String address) {
- this.address = address;
- }
- @Override
- public String toString() {
- return "Person [id=" + id + ", name=" + name + ", age=" + age
- + ", address=" + address + "]";
- }
-
-
-
- }
复制代码 2、TreeSetC类- package edu.sdp.java.demo;
- import java.util.Comparator;
- import java.util.Iterator;
- import java.util.TreeSet;
- public class TreeSetC {
- public static void main(String[] args) {
-
-
- Comparator com = new Comparator(){
- @Override
- public int compare(Object o1, Object o2) {
- Person oo1 = (Person)o1;
- Person oo2 = (Person)o2;
- if (oo1.getAge() > oo2.getAge()) {
- return 1;
- }else if(oo1.getAge() < oo2.getAge()){
- return -1;
- }else{
- return 0;
- }
- }
- };
-
-
- TreeSet set = new TreeSet(com);
-
- Person p1 = new Person(2,"旺财",28,"济南");
- Person p2 = new Person(3,"王超",18,"临沂");
- Person p3 = new Person(1,"高向阳",21,"鱼台");
-
- set.add(p1);
- set.add(p2);
- set.add(p3);
-
-
- Iterator iter = set.iterator();//遍历
-
- while(iter.hasNext()){
- System.out.println(iter.next());
- }
- }
-
- }
复制代码 |
|