函數式編程+比較器

比較器編程

@FunctionalInterface
public interface Comparator<T> {數組

    int compare(T o1, T o2);ide

}函數

@FunctionalInterface  指的是功能性函數接口,裏面只有一個方法。    this

對於Comparable接口來講,它每每是進行比較類須要實現的接口,它僅包含一個有compareTo()方法,只有一個參數,返回值爲int,返回值大於0表示對象大於參數對象;小於0表示對象小於參數對象;等於0表示二者相等spa

 

public class Demo { public static class Student { public String name; public int id; public int age; public Student(String name, int id, int age) { this.name = name; this.id = id; this.age = age; } @Override public String toString() { return "Name : " + this.name + ", Id : " + this.id + ", Age : " + this.age; } } public static Student[] create(){ return new Student[] { new Student("A", 1, 23), new Student("B", 2, 21), new Student("C", 2, 20), new Student("E", 2, 19), new Student("D", 2, 29), new Student("F", 1, 24) }; } public static void printArr(Student[] array){ for (int i = 0; i < array.length; i++) { System.out.println(array[i]); } System.out.println("========================\n"); } public static void main(String[] args) { printArr(create()); } }

基礎類Student被create()實例化爲數組形式,經過printArr打印Student的信息。code

 

比較器對象

在Demo中實現Comparator接口blog

public static class AgeDescendingComparator implements Comparator<Student> { @Override public int compare(Student o1, Student o2) { return o2.age - o1.age; } }

而後就是在main方法中引用,排序

public static void main(String[] args) { Student[] students = create(); printArr(students); Arrays.sort(students, new AgeDescendingComparator()); printArr(students); }

結果爲學生年齡降序排列:

Name : A, Id : 1, Age : 23
Name : B, Id : 2, Age : 21
Name : C, Id : 2, Age : 20
Name : E, Id : 2, Age : 19
Name : D, Id : 2, Age : 29
Name : F, Id : 1, Age : 24
========================

Name : D, Id : 2, Age : 29
Name : F, Id : 1, Age : 24
Name : A, Id : 1, Age : 23
Name : B, Id : 2, Age : 21
Name : C, Id : 2, Age : 20
Name : E, Id : 2, Age : 19
========================

 

函數值編程

可是每次都要自定義類實現comparator接口,過於繁雜,有關函數式接口的其餘應用,網上有不少。

在main中

Comparator<Student> nameAort = (st1,st2) -> {return st1.name.compareTo(st2.name);};

在構建以年齡排序的小根堆

PriorityQueue<Student> heap = new PriorityQueue<>(nameAort);// 小根堆
        for (int i = 0; i < students.length; i++) { heap.add(students[i]); } while (!heap.isEmpty()) { Student student = heap.poll(); System.out.println(student); }

如今到底結果

Name : A, Id : 1, Age : 23Name : B, Id : 2, Age : 21Name : C, Id : 2, Age : 20Name : D, Id : 2, Age : 29Name : E, Id : 2, Age : 19Name : F, Id : 1, Age : 24

相關文章
相關標籤/搜索