java三元运算符
int a = 10;
int b = 20;
a==b?10:20; 结果为20
Long型集合排序
Java 多字段排序Comparator(兼容Date,Integer,Doubel,Long)
有一个需求,需要对long型时间进行排序,但是使用了compareTo排序方法并不能正确打印顺序,比如下面的方法
/**
* 错误排序
*/
public static void longPaiXu() {
List<String> list = new ArrayList<String>();
list.add(String.valueOf(1111111116));
list.add(String.valueOf(1111111));
list.add(String.valueOf(1111111119));
list.add(String.valueOf(1111113));
list.add(String.valueOf(11117));
list.add(String.valueOf(11111114));
list.add(String.valueOf(11112));
list.add(String.valueOf(1111111111));
list.add(String.valueOf(1111111118));
Collections.sort(list,new MyComparator());
Collections.sort(list);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i)+" ");
}
}
```
```
package com.hjh.zhyw;
import java.util.Comparator;
public class MyComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
// TODO Auto-generated method stub
System.out.println(o1.compareTo(o2));
return o1.compareTo(o2);
}
}
```
后来网上搜索了一下,找到这个代码,大概是Date、String使用compareTo比较,Integer、Long、Double使用">"或者"<"比较
```
@Override
public int compare(Object o1, Object o2) {
int result = 0;
for (String file : filed) {
Object value1 = ReflexUtil.invokeMethod(file, o1);
Object value2 = ReflexUtil.invokeMethod(file, o2);
if (value1 == null || value2 == null) {
continue;
}
if (value1 instanceof Integer) { //Integer整数序排序
int v1 = Integer.valueOf(value1.toString());
int v2 = Integer.valueOf(value2.toString());
if (v1 == v2) continue;
if (sort == 1) {
return v1 - v2;
} else if (sort == -1) {
return v2 - v1;
}
} else if (value1 instanceof Date) { //Date类型排序
Date d1 = (Date) value1;
Date d2 = (Date) value2;
if (d1.compareTo(d2) == 0) continue;
if (sort == 1) {
return d1.compareTo(d2);
} else if (sort == -1) {
return d2.compareTo(d1);
}
} else if (value1 instanceof Long) { //Long排序
long v1 = Long.valueOf(value1.toString());
long v2 = Long.valueOf(value2.toString());
if (v1 == v2) continue;
if (sort == 1) {
return v1 > v2 ? 1 : -1;
} else if (sort == -1) {
return v2 > v1 ? 1 : -1;
}
} else if (value1 instanceof Double) { //Double排序
Double v1 = Double.valueOf(value1.toString());
Double v2 = Double.valueOf(value2.toString());
if (v1 == v2) continue;
if (sort == 1) {
return v1 > v2 ? 1 : -1;
} else if (sort == -1) {
return v2 > v1 ? 1 : -1;
}
}
}
```
网友评论