当前位置:网站首页>Comparable and comparator of sorting
Comparable and comparator of sorting
2022-07-07 14:55:00 【nsnsttn】
Comparable<T>
and Comparator<T>
These two interfaces are often used , Here is what these two are and how to use them
Comparable<T> and Comparator<T> It is generally used to sort objects ,
Comparable<T> It's an internal comparator ,Comparator<T> It's an external comparator , Take a look at the examples directly from the code
1.Comparable<T>
Comparable<T>
Internal comparator , So those who need sorting ability can realize it
Usage mode
1. If we want to List<SortA> Sort in a certain way , Can be SortA Realization Comparable<SortA>
Interface , rewrite compareTo(SortA s)
Method
@Data
public class SortA implements Serializable, Comparable<SortA>{
@ApiModelProperty(" name ")
private String name;
@ApiModelProperty(" Age ")
private Integer age;
// Custom collation
@Override
public int compareTo(SortA o) {
return this.age - o.getAge(); // Ascending
//return this.age.compareTo( o.getAge()); // Ascending
//return o.getAge() - this.age; // In reverse order
//return o.getAge().compareTo(this.age); // In reverse order
//return -1; // Reverse order of natural sorting
//return 1 or 0; // Natural ordering
}
}
public class Sort {
public static void main(String[] args) {
// Creating data
List<SortA> listA = new ArrayList<>();
SortA a1 = new SortA();
a1.setName("a Zhang San ");
a1.setAge(18);
SortA a2 = new SortA();
a2.setName("c Li Si ");
a2.setAge(16);
SortA a3 = new SortA();
a3.setName("b Wang Wu ");
a3.setAge(17);
listA.add(a1);
listA.add(a2);
listA.add(a3);
// Calling method
testComparable(listA);
}
public static void testComparable(List<SortA> listA) {
// Sorting method Collections.sort(List<T> list);
// For internal use Arrays.sort(a, (Comparator) c);
// So if the data is an array , It can be used directly Arrays.sort( data ) Sort by
Collections.sort(listA);
System.out.println("Comparable Sort :" + listA);
//Comparable Sort :[SortA(name= Li Si , age=16), SortA(name= Wang Wu , age=17), SortA(name= Zhang San , age=18)]
}
}
2.Comparator<T>
We can find out Comparable<T>
The code is more intrusive , And not flexible enough , The sorting rules of the same object cannot be the same every time , Then you can use the external comparator Comparator<T>
Usage mode
2.1 Comparator Can not help SortA Realization , You can implement a SortAComparator Sorting class
// Note that generics are classes that need sorting SortA
public class SortAComparator implements Comparator<SortA> {
/** * compare() and compareTo() It's like , Return value reference compareTo(),o1 amount to this */
@Override
public int compare(SortA o1, SortA o2) {
int sort = o1.getAge() - o2.getAge();
return sort;
}
}
2.2 Comparable Is a functional interface , So you can use anonymous inner classes or Lambda expression ( Commonly used ) To achieve
even to the extent that jdk8 in the future Comparable<T> It provides a lot of static Methods are directly available to us
2.3 Go straight to the code
public class Sort {
public static void main(String[] args) {
// Creating data
List<SortA> listA = new ArrayList<>();
SortA a1 = new SortA();
a1.setName("a Zhang San ");
a1.setAge(18);
SortA a2 = new SortA();
a2.setName("c Li Si ");
a2.setAge(16);
SortA a3 = new SortA();
a3.setName("b Wang Wu ");
a3.setAge(17);
listA.add(a1);
listA.add(a2);
listA.add(a3);
// Calling method
testComparator(listA);
}
public static void testComparator(List<SortA> listA) {
// External comparator , Realization Comparator Interface
//1.SortAComparator Realization Comparator Interface
listA.sort(new SortAComparator());
System.out.println(listA);
//2. Use anonymous inner classes or Lambda, expression
listA.sort(new Comparator<SortA>() {
@Override
public int compare(SortA o1, SortA o2) {
// Age in reverse order
return o2.getAge() - o1.getAge();
}
});
//3. Use anonymous inner classes or Lambda or Comparator Static method of "
//3.1 Sort by name in positive order
listA.sort(Comparator.comparing(SortA::getName));
System.out.println(listA);
//3.2 Sort by name in reverse
listA.sort(Comparator.comparing(SortA::getName).reversed());
System.out.println(listA);
listA.sort(Comparator.comparing(SortA::getName,Comparator.reverseOrder()));
System.out.println(listA);
}
}
Pay attention to multiple conditions !!
reversed and Comparator.reverseOrder() The timing of reversing the order is different
Comparator.reverseOrder() This attribute will be sorted immediately
reversed() You will get the results on the left and sort
therefore
Comparator.reverseOrder() It is only for the inversion of the current attribute ,
reversed() Will reverse all sorts on the left , Just pay attention to this
Up test ~~
public class Sort {
public static void main(String[] args) {
List<SortA> listA = new ArrayList<>();
SortA a1 = new SortA();
a1.setName("a");
a1.setAge(18);
SortA a2 = new SortA();
a2.setName("a");
a2.setAge(19);
SortA a3 = new SortA();
a3.setName("b");
a3.setAge(17);
SortA a4 = new SortA();
a4.setName("c");
a4.setAge(17);
SortA a5 = new SortA();
a5.setName("d");
a5.setAge(15);
listA.add(a1);
listA.add(a2);
listA.add(a3);
listA.add(a4);
listA.add(a5);
moreComparator(listA);
}
public static void moreComparator(List<SortA> listA){
//1.name positive sequence ,name equally age positive sequence
listA.sort(Comparator.comparing(SortA::getName).thenComparing(SortA::getAge));
System.out.println(listA);
//2.name In reverse order ,name equally age positive sequence
listA.sort(Comparator.comparing(SortA::getName).reversed().thenComparing(SortA::getAge));
System.out.println(listA); listA.sort(Comparator.comparing(SortA::getName,Comparator.reverseOrder()).thenComparing(SortA::getAge));
System.out.println(listA);
//3.name In reverse order ,name equally age In reverse order
listA.sort(Comparator.comparing(SortA::getName).thenComparing(SortA::getAge).reversed());
System.out.println(listA);
listA.sort(Comparator.comparing(SortA::getName,Comparator.reverseOrder()).thenComparing(SortA::getAge,Comparator.reverseOrder()));
System.out.println(listA);
//4.name positive sequence ,name equally age In reverse order
listA.sort(Comparator.comparing(SortA::getName).reversed().thenComparing(SortA::getAge).reversed());
System.out.println(listA);
listA.sort(Comparator.comparing(SortA::getName).thenComparing(SortA::getAge,Comparator.reverseOrder()));
System.out.println(listA);
}
}
Note that the object or attribute is empty
public class Sort {
public static void main(String[] args) {
List<SortA> listA = new ArrayList<>();
SortA a1 = new SortA();
a1.setName("a");
a1.setAge(18);
SortA a2 = new SortA();
a2.setName("a");
a2.setAge(19);
SortA a3 = new SortA();
a3.setName("b");
a3.setAge(17);
SortA a4 = new SortA();
a4.setName("c");
a4.setAge(17);
SortA a5 = new SortA();
// a5.setName("d");
a5.setAge(15);
listA.add(a1);
listA.add(a2);
listA.add(a3);
listA.add(a4);
listA.add(a5);
listA.add(null);
nullComparator(listA);
}
// If the object or attribute is empty
public static void nullComparator(List<SortA> listA){
//1. If the object is empty
listA.sort(Comparator.nullsFirst(Comparator.comparing(SortA::getName,Comparator.nullsFirst(Comparator.naturalOrder()))));
System.out.println(listA);
//2. If name It's empty
// Natural ordering
listA.sort(Comparator.comparing(SortA::getName,Comparator.nullsFirst(Comparator.naturalOrder())));
listA.sort(Comparator.comparing(SortA::getName,Comparator.nullsFirst(String::compareTo)));
System.out.println(listA);
// reverse
listA.sort(Comparator.comparing(SortA::getName,Comparator.nullsFirst(Comparator.reverseOrder())));
System.out.println(listA);
}
}
summary :
Comparable<T>
It's an internal comparator ,Comparator<T>
It's an external comparatorThe most recommended use is
Comparator<T>
Interface sortingComparator
It is convenient to provide static methods , Recommended , Those who don't know can learn functional interfaces first 、Lambda、 Method referenceComparator
Pay attention to when sorting with multiple conditions Comparator.reverseOrder() and reversed() Use ,Comparator
When sorting, pay attention to the situation that objects and attributes may be empty , Use Comparator.nullsFirst() perhaps Comparator.nullsLast()
边栏推荐
- Niuke real problem programming - Day10
- 一款你不容错过的Laravel后台管理扩展包 —— Voyager
- “百度杯”CTF比赛 2017 二月场,Web:include
- Classification of regression tests
- 上半年晋升 P8 成功,还买了别墅!
- Ian Goodfellow, the inventor of Gan, officially joined deepmind as research scientist
- Niuke real problem programming - Day9
- ⼀个对象从加载到JVM,再到被GC清除,都经历了什么过程?
- PLC: automatically correct the data set noise, wash the data set | ICLR 2021 spotlight
- Discussion on CPU and chiplet Technology
猜你喜欢
CTFshow,信息搜集:web6
EfficientNet模型的完整细节
Jetson AGX Orin CANFD 使用
Niuke real problem programming - Day17
智汀不用Home Assistant让小米智能家居接入HomeKit
Instructions for mictr01 tester vibrating string acquisition module development kit
Wechat applet - Advanced chapter component packaging - Implementation of icon component (I)
Data Lake (IX): Iceberg features and data types
Cvpr2022 | backdoor attack based on frequency injection in medical image analysis
Pandora IOT development board learning (HAL Library) - Experiment 12 RTC real-time clock experiment (learning notes)
随机推荐
解析PHP跳出循环的方法以及continue、break、exit的区别介绍
CTFshow,信息搜集:web3
13 ux/ui/ue best creative inspiration websites in 2022
Promoted to P8 successfully in the first half of the year, and bought a villa!
Several ways of JS jump link
Base64 encoding
激光雷達lidar知識點滴
Es log error appreciation -trying to create too many buckets
属性关键字OnDelete,Private,ReadOnly,Required
The world's first risc-v notebook computer is on pre-sale, which is designed for the meta universe!
AWS learning notes (III)
Computer win7 system desktop icon is too large, how to turn it down
asp.netNBA信息管理系统VS开发sqlserver数据库web结构c#编程计算机网页源码项目详细设计
缓冲区溢出保护
Niuke real problem programming - Day9
Niuke real problem programming - Day10
EfficientNet模型的完整细节
Niuke real problem programming - day15
Bill Gates posted his resume 48 years ago: "it's not as good-looking as yours."
电脑Win7系统桌面图标太大怎么调小