当前位置:网站首页>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()
边栏推荐
- EfficientNet模型的完整细节
- "July 2022" Wukong editor update record
- 拜拜了,大厂!今天我就要去厂里
- Pinduoduo lost the lawsuit, and the case of bargain price difference of 0.9% was sentenced; Wechat internal test, the same mobile phone number can register two account functions; 2022 fields Awards an
- Ffmpeg --- image processing
- ⼀个对象从加载到JVM,再到被GC清除,都经历了什么过程?
- CTFshow,信息搜集:web2
- Es log error appreciation -- allow delete
- CTFshow,信息搜集:web4
- Ian Goodfellow, the inventor of Gan, officially joined deepmind as research scientist
猜你喜欢
CTFshow,信息搜集:web10
Niuke real problem programming - day13
CTFshow,信息搜集:web12
In the field of software engineering, we have been doing scientific research for ten years!
What is cloud primordial? This time, I can finally understand!
Internal sort - insert sort
AWS学习笔记(三)
Cocoscreator operates spine for animation fusion
「2022年7月」WuKong编辑器更版记录
Discussion on CPU and chiplet Technology
随机推荐
8大模块、40个思维模型,打破思维桎梏,满足你工作不同阶段、场景的思维需求,赶紧收藏慢慢学
PG basics -- Logical Structure Management (locking mechanism -- table lock)
Summary on adding content of background dynamic template builder usage
The world's first risc-v notebook computer is on pre-sale, which is designed for the meta universe!
JSON parsing instance (QT including source code)
Cocoscreator operates spine for animation fusion
Read PG in data warehouse in one article_ stat
CTFshow,信息搜集:web12
Navigation — 这么好用的导航框架你确定不来看看?
MicTR01 Tester 振弦采集模块开发套件使用说明
"July 2022" Wukong editor update record
C 6.0 language specification approved
Pytorch model trains practical skills and breaks through the bottleneck of speed
Lidar knowledge drops
Leetcode one question per day (636. exclusive time of functions)
Cocos creator direction and angle conversion
CTFshow,信息搜集:web3
A laravel background management expansion package you can't miss - Voyager
6. Electron borderless window and transparent window lock mode setting window icon
15、文本编辑工具VIM使用