1.List中存放基本数据类型
排序:使用Collections.sort(list,new Comparator(T)),重新compare方法;
List<String> list = new ArrayList<String>();
list.add("aa");
list.add("cc");
list.add("bb");
System.out.println("排序前:");
for (String string : list) {
System.out.println(string);
}
Collections.sort(list,new Comparator<String>() {
public int compare(String item1, String item2) {
if (item1.compareTo(item2) > 0) {
return 1;
}else if (item1.compareTo(item2) < 0) {
return -1;
}else {
return 0;
}
}
});
System.out.println("排序前:");
for (String string : list) {
System.out.println(string);
}
}
结果:
2.List中存放对象,如果要对List进行排序,两种方法:
第一种方法:对象实现Comparable<T>接口,重新compareTo方法:
public class JavaTest {
public static void main(String[] args) {
List<B> bList = new ArrayList<B>();
B a = new B(1);
B b = new B(3);
B c = new B(2);
bList.add(a);
bList.add(b);
bList.add(c);
System.out.println("排序前:");
for (B b2 : bList) {
System.out.println(b2);
}
Collections.sort(bList);
System.out.println("排序后:");
for (B b2 : bList) {
System.out.println(b2);
}
}
}
class B implements Comparable<B>{
int index;
public B() {
super();
}
public B(int index) {
super();
this.index = index;
}
@Override
public String toString() {
return "B [index=" + index + "]";
}
/**
* @Description: TODO
* @param o
* @return
* @date 2018年6月4日
*/
public int compareTo(B item) {
return this.index - item.index;
}
}
结果:
第二种方法:自定义比较器
public class JavaTest {
public static void main(String[] args) {
List<B> bList = new ArrayList<B>();
B a = new B(1);
B b = new B(3);
B c = new B(2);
bList.add(a);
bList.add(b);
bList.add(c);
System.out.println("排序前:");
for (B b2 : bList) {
System.out.println(b2);
}
Collections.sort(bList,new MyComparator());
System.out.println("排序后:");
for (B b2 : bList) {
System.out.println(b2);
}
}
}
class B{
int index;
public B() {
super();
}
public B(int index) {
super();
this.index = index;
}
@Override
public String toString() {
return "B [index=" + index + "]";
}
}
class MyComparator implements Comparator<B>{
/**
* @Description: TODO 重新compare方法
* @param o1
* @param o2
* @return
* @date 2018年6月4日
*/
public int compare(B o1, B o2) {
return o2.index - o1.index;
}
}
结果:
3.第三种方法:类似第二种方法,使用comparator的内部类
public class JavaTest {
public static void main(String[] args) {
List<B> bList = new ArrayList<B>();
B a = new B(1);
B b = new B(3);
B c = new B(2);
bList.add(a);
bList.add(b);
bList.add(c);
System.out.println("排序前:");
for (B b2 : bList) {
System.out.println(b2);
}
Collections.sort(bList,new Comparator<B>() {
public int compare(B o1, B o2) {
return o1.index - o2.index;
}
});
System.out.println("排序后:");
for (B b2 : bList) {
System.out.println(b2);
}
}
}
class B{
int index;
public B() {
super();
}
public B(int index) {
super();
this.index = index;
}
@Override
public String toString() {
return "B [index=" + index + "]";
}
}
结果: