Java之Comparator使用舉例


簡介

Comparator是一個比較器接口,位於java.util包下,用於排序和比較。

代碼舉例

import java.util.*;

/**
 * @author :gongxr
 * @description:Comparator比較器
 */
@Slf4j
public class ComparatorDemo {
    public List<User> getList() {
        List<User> users = new ArrayList<>();
        User user = new User("Tom", 22, "Street #1");
        users.add(user);
        users.add(new User("Michael", 33, "Street #2"));
        users.add(new User("Lily", 25, "Street #3"));
        return users;
    }

    @Test
    public void testComparator() {
        List<User> users = getList();

        /*查詢年齡最大的人*/
        Optional<User> max = users.stream().max(Comparator.comparing(User::getAge));
        log.info("maxAge: " + max.get().toString());

        /*名字最長的人*/
        Optional<String> max2 = users.stream().map(u -> u.getName()).max(Comparator.comparing(String::length));
        log.info("maxStringLength: " + max2.get());
    }


    /**
     * 排序
     * 在List或數組中的對象如果沒有實現Comparable接口時,那么就需要調用者為需要排序的數組或List設置一個Compartor,
     * Compartor的compare方法用來告訴代碼應該怎么去比較兩個實例,然后根據比較結果進行排序
     */
    class Dog {
        public int age;
        public String name;

        public Dog(int age, String name) {
            super();
            this.age = age;
            this.name = name;
        }

        @Override
        public String toString() {
            return "Dog [age=" + age + ", name=" + name + "]";
        }
    }

    @Test
    public void test1() {
        List<Dog> list = new ArrayList<>();
        list.add(new Dog(5, "DogA"));
        list.add(new Dog(6, "DogB"));
        list.add(new Dog(7, "DogC"));
        Collections.sort(list, new Comparator<Dog>() {
            @Override
            public int compare(Dog o1, Dog o2) {
                return o2.age - o1.age;
            }
        });
        System.out.println("給狗狗按照年齡倒序:" + list);

        Collections.sort(list, new Comparator<Dog>() {
            @Override
            public int compare(Dog o1, Dog o2) {
                return o1.name.compareTo(o2.name);
            }
        });
        System.out.println("給狗狗按名字字母順序排序:" + list);
    }


    /**
     * 分組
     * 使用Comparator和for循環處理列表,來進行分類;通過調用者實現Comparator接口的比較邏輯,來告訴程序應該怎么比較,通過比較之后得結果來進行分組。
     * 下面例子中分別按照狗狗的顏色和體重級別兩個維度來進行分組,因此分組的核心邏輯其實就是比較邏輯。
     * 下面抽了一個工具方法:dividerList,第一個參數為需要處理的數據源,第二參數是分組時的比較邏輯。
     */
    class Apple {
        public String color;
        public int weight;

        public Apple(String color, int weight) {
            super();
            this.color = color;
            this.weight = weight;
        }

        @Override
        public String toString() {
            return "Apple [color=" + color + ", weight=" + weight + "]";
        }
    }

    /*按條件分組*/
    public static <T> List<List<T>> divider(Collection<T> datas, Comparator<? super T> c) {
        List<List<T>> result = new ArrayList<List<T>>();
        for (T t : datas) {
            boolean isSameGroup = false;
            for (int j = 0; j < result.size(); j++) {
                if (c.compare(t, result.get(j).get(0)) == 0) {
                    isSameGroup = true;
                    result.get(j).add(t);
                    break;
                }
            }
            if (!isSameGroup) {
                // 創建
                List<T> innerList = new ArrayList<T>();
                result.add(innerList);
                innerList.add(t);
            }
        }
        return result;
    }

    @Test
    public void test2() {
        List<Apple> list = new ArrayList<>();
        list.add(new Apple("紅", 205));
        list.add(new Apple("紅", 131));
        list.add(new Apple("綠", 248));
        list.add(new Apple("綠", 153));
        list.add(new Apple("紅", 332));
        list.add(new Apple("黃", 119));
        list.add(new Apple("黃", 224));
        List<List<Apple>> byColors = divider(list, new Comparator<Apple>() {
            @Override
            public int compare(Apple o1, Apple o2) {
                // 按顏色分組
                return o1.color.compareTo(o2.color);
            }
        });
        System.out.println("按顏色分組" + byColors);

        List<List<Apple>> byWeight = divider(list, new Comparator<Apple>() {
            @Override
            public int compare(Apple o1, Apple o2) {
                // 按重量級

                return (o1.weight / 100 == o2.weight / 100) ? 0 : 1;
            }
        });
        System.out.println("按重量級分組" + byWeight);
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM