一、自定义class使用collections工具类排序比较
//通过Collections工具类,对某个自定义类进行排序
Collections.sort(sortList, WordCounter.CASE_INSENSITIVE_ORDER);//该例子是对单词类忽略大小写排序
第二个参数是需要在类中通过new一个comparator类进行自定义的。
下面举个简单的例子
二、测试用例
集合类中可以传入比较器作为排序规则,需要在比较的自定义类中添加自定义比较方法,如下定义:
import java.util.Comparator;
public class WordContainer{
//在类中自定义一个比较器规则
public static final Comparator<WordContainer> CASE_INSENSITIVE_ORDER = new
Comparator<WordContainer>() {
@Override
public int compare(WordContainer o1, WordContainer o2) {
//在这写比较器规则 (正数:o1>o2;零:o1=o2;负数o1<o2)
return o1.word.compareToIgnoreCase(o2.word);
}};
private String id;
private String word;
public String getWord() {
return word;
}
public WordContainer(String id, String word) {
this.id = id;
this.word = word;
}
}
验证方法:
package com.geng.word;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class WordSort {
public static void main(String[] args) {
WordContainer o1=new WordContainer("1", "tom");
WordContainer o2=new WordContainer("3", "bob");
WordContainer o3=new WordContainer("6", "Catelina");
WordContainer o4=new WordContainer("2", "Boss");
List<WordContainer> sortList=new ArrayList<>();
sortList.add(o1);
sortList.add(o2);
sortList.add(o3);
sortList.add(o4);
System.out.println("-------------排序前-------------");
for (WordContainer wordContainer : sortList) {
System.out.println(wordContainer.getWord().toString());
}
Collections.sort(sortList, WordContainer.CASE_INSENSITIVE_ORDER);
System.out.println("-------------排序后-------------");
for (WordContainer wordContainer : sortList) {
System.out.println(wordContainer.getWord().toString());
}
}
}
输出结果:
本例用到的比较:
str1.compareToIgnoreCase(str2);
str1与str2进行忽略大小写比较,从左往右按位比较