Comparator用法

Comparator  不同于 Comparable

java.util.Comparator

DEMO

----------------------------------------

Lake湖类

class Lake {
    private String name = "淡水湖";
    private String englishName = "lake";
    private int area = 1;
   
    public Lake(String n, String e, int a) {
        setName(n);
        setEnglishName(e);
        setArea(a);
    }
   
    public String getName() {
        return name;
    }
    public boolean setName(String n) {
        if(n != null && n.length() > 0) {
            name = n;
            return true;
        }
        return false;
    }
    public String getEnglishName() {
        return englishName;
    }
    public boolean setEnglishName(String e) {
        if(e != null && e.length() > 0) {
            englishName = e;
            return true;
        }
        return false;
    }
    public int getArea() {
        return area;
    }
    public boolean setArea(int a) {
        if(a >= 1 && a <= 10000) {
            area = a;
            return true;
        }
        return false;
    }
   
    public String toString() {
        return name + " (" + englishName + ", " + area + "平方公里)";
    }
}
-----------------------

按大小排序

import java.util.Comparator;

class AreaComparator implements Comparator<Lake> {
    public int compare(Lake k1, Lake k2) {
        return k1.getArea() - k2.getArea();
    }
}

-----------------------

按名字排序

import java.util.Comparator;

class NameComparator implements Comparator<Lake> {
    public int compare(Lake k1, Lake k2) {
        return k1.getEnglishName().compareTo(k2.getEnglishName());
    }
}

-----------------------

测试类

import java.util.*;

class FiveLakes {
    public static void main(String[] args) {
        ArrayList<Lake> lakes = new ArrayList<Lake>();
       
        lakes.add(new Lake("洞庭湖", "Dongting Lake", 2820));
        lakes.add(new Lake("太湖", "Lake Thai", 2250));
        lakes.add(new Lake("巢湖", "Chao Lake", 775));
        lakes.add(new Lake("鄱阳湖", "Po-yang Lake", 3914));
        lakes.add(new Lake("洪泽湖", "Hung-tse Lake", 1577));
       
        Collections.sort(lakes, new NameComparator());
        System.out.println("我国的五大淡水湖, 按\"英文名称\"[升序]排列如下:");
        for(int i = 0; i < 5; i++) {
            System.out.println(i+1 + ". " + lakes.get(i));
        }
       
        System.out.println();
        Collections.sort(lakes, new AreaComparator());
        Collections.reverse(lakes);
        System.out.println("我国的五大淡水湖, 按湖水面积[降序]排列如下:");
        for(int i = 0; i < 5; i++) {
            System.out.println(i+1 + ". " + lakes.get(i));
        }
    }
}

 

上一篇:面试官:说一下List排序方法


下一篇:JavaSE-15.2.4【案例-成绩排序(比较器排序Comparator实现、自然排序Comparable实现)】