当前位置:网站首页>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()
边栏推荐
- Emqx 5.0 release: open source Internet of things message server with single cluster supporting 100million mqtt connections
- Mlgo: Google AI releases industrial compiler optimized machine learning framework
- How bad can a programmer be? Nima, they are all talents
- word中删除一整页
- asp.netNBA信息管理系统VS开发sqlserver数据库web结构c#编程计算机网页源码项目详细设计
- Navigation - are you sure you want to take a look at such an easy-to-use navigation framework?
- 激光雷達lidar知識點滴
- EMQX 5.0 发布:单集群支持 1 亿 MQTT 连接的开源物联网消息服务器
- Introduction and use of Kitti dataset
- 防火墙基础之服务器区的防护策略
猜你喜欢
WebRTC 音频抗弱网技术(上)
Zhiting doesn't use home assistant to connect Xiaomi smart home to homekit
Huawei cloud database DDS products are deeply enabled
CTFshow,信息搜集:web1
“百度杯”CTF比赛 2017 二月场,Web:include
上半年晋升 P8 成功,还买了别墅!
Niuke real problem programming - Day10
全球首款 RISC-V 笔记本电脑开启预售,专为元宇宙而生!
CTFshow,信息搜集:web5
Instructions for mictr01 tester vibrating string acquisition module development kit
随机推荐
解析PHP跳出循环的方法以及continue、break、exit的区别介绍
属性关键字OnDelete,Private,ReadOnly,Required
Cocos creator direction and angle conversion
JS in the browser Base64, URL, blob mutual conversion
Jetson AGX Orin CANFD 使用
Five pain points for big companies to open source
什么是云原生?这回终于能搞明白了!
Novel Slot Detection: A Benchmark for Discovering Unknown Slot Types in the Dialogue System
word中删除一整页
leetcode:648. Word replacement [dictionary tree board + find the shortest matching prefix among several prefixes]
15、文本编辑工具VIM使用
Niuke real problem programming - day13
Ian Goodfellow, the inventor of Gan, officially joined deepmind as research scientist
Apache multiple component vulnerability disclosure (cve-2022-32533/cve-2022-33980/cve-2021-37839)
PAG体验:十分钟完成AE动效部署上线各平台!
全球首款 RISC-V 笔记本电脑开启预售,专为元宇宙而生!
Niuke real problem programming - Day10
Ascend 910 realizes tensorflow1.15 to realize the Minist handwritten digit recognition of lenet network
CTFshow,信息搜集:web13
Navigation - are you sure you want to take a look at such an easy-to-use navigation framework?