当前位置:网站首页>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 sortingComparatorIt is convenient to provide static methods , Recommended , Those who don't know can learn functional interfaces first 、Lambda、 Method referenceComparatorPay attention to when sorting with multiple conditions Comparator.reverseOrder() and reversed() Use ,ComparatorWhen sorting, pay attention to the situation that objects and attributes may be empty , Use Comparator.nullsFirst() perhaps Comparator.nullsLast()
边栏推荐
- Jetson AGX Orin CANFD 使用
- Navigation — 这么好用的导航框架你确定不来看看?
- buffer overflow protection
- Decrypt the three dimensional design of the game
- What is cloud primordial? This time, I can finally understand!
- 全球首款 RISC-V 笔记本电脑开启预售,专为元宇宙而生!
- Niuke real problem programming - day14
- Navigation - are you sure you want to take a look at such an easy-to-use navigation framework?
- FFmpeg----图片处理
- CTFshow,信息搜集:web2
猜你喜欢

「2022年7月」WuKong编辑器更版记录

#yyds干货盘点# 解决名企真题:交叉线

15、文本编辑工具VIM使用

Novel Slot Detection: A Benchmark for Discovering Unknown Slot Types in the Dialogue System

MicTR01 Tester 振弦采集模塊開發套件使用說明

Ian Goodfellow, the inventor of Gan, officially joined deepmind as research scientist

How to enable radius two factor / two factor (2fa) identity authentication for Anheng fortress machine

上半年晋升 P8 成功,还买了别墅!

Navigation — 这么好用的导航框架你确定不来看看?

大厂做开源的五大痛点
随机推荐
数据库如何进行动态自定义排序?
asp. Netnba information management system VS development SQLSERVER database web structure c programming computer web page source code project detailed design
JS image to Base64
PLC: automatically correct the data set noise, wash the data set | ICLR 2021 spotlight
JS in the browser Base64, URL, blob mutual conversion
CTFshow,信息搜集:web10
Navigation - are you sure you want to take a look at such an easy-to-use navigation framework?
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
Attribute keywords ondelete, private, readonly, required
Decrypt the three dimensional design of the game
广州开发区让地理标志产品助力乡村振兴
AWS learning notes (III)
The method of parsing PHP to jump out of the loop and the difference between continue, break and exit
CTFshow,信息搜集:web12
Small game design framework
防火墙基础之服务器区的防护策略
Base64 encoding
CTFshow,信息搜集:web13
Niuke real problem programming - Day9
Half an hour of hands-on practice of "live broadcast Lianmai construction", college students' resume of technical posts plus points get!