当前位置:网站首页>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()
边栏推荐
- Stm32cubemx, 68 sets of components, following 10 open source protocols
- Five pain points for big companies to open source
- 用于增强压缩视频质量的可变形卷积密集网络
- 8大模块、40个思维模型,打破思维桎梏,满足你工作不同阶段、场景的思维需求,赶紧收藏慢慢学
- Internal sort - insert sort
- 时空可变形卷积用于压缩视频质量增强(STDF)
- Bill Gates posted his resume 48 years ago: "it's not as good-looking as yours."
- Nllb-200: meta open source new model, which can translate 200 languages
- A laravel background management expansion package you can't miss - Voyager
- 13 ux/ui/ue best creative inspiration websites in 2022
猜你喜欢

Today's sleep quality record 78 points

Navigation - are you sure you want to take a look at such an easy-to-use navigation framework?

Infinite innovation in cloud "vision" | the 2022 Alibaba cloud live summit was officially launched

数据湖(九):Iceberg特点详述和数据类型

2022pagc Golden Sail award | rongyun won the "outstanding product technology service provider of the year"

CTFshow,信息搜集:web7

Niuke real problem programming - day14

防火墙基础之服务器区的防护策略

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

拼多多败诉,砍价始终差0.9%一案宣判;微信内测同一手机号可注册两个账号功能;2022年度菲尔兹奖公布|极客头条...
随机推荐
IDA pro逆向工具寻找socket server的IP和port
《微信小程序-进阶篇》组件封装-Icon组件的实现(一)
asp. Netnba information management system VS development SQLSERVER database web structure c programming computer web page source code project detailed design
“百度杯”CTF比赛 2017 二月场,Web:include
PyTorch模型训练实战技巧,突破速度瓶颈
数据湖(九):Iceberg特点详述和数据类型
Attribute keywords serveronly, sqlcolumnnumber, sqlcomputecode, sqlcomputed
大厂做开源的五大痛点
Attribute keywords ondelete, private, readonly, required
Es log error appreciation -trying to create too many buckets
Niuke real problem programming - Day11
FFmpeg----图片处理
Half an hour of hands-on practice of "live broadcast Lianmai construction", college students' resume of technical posts plus points get!
CTFshow,信息搜集:web13
AWS learning notes (III)
属性关键字ServerOnly,SqlColumnNumber,SqlComputeCode,SqlComputed
电脑Win7系统桌面图标太大怎么调小
数据库如何进行动态自定义排序?
Read PG in data warehouse in one article_ stat
Niuke real problem programming - day18