Emi*_*mil 6 java sorting collections list
如何排序List<Number>?
例:
List<Number> li = new ArrayList<Number>(); //list of numbers
li.add(new Integer(20));
li.add(new Double(12.2));
li.add(new Float(1.2));
Run Code Online (Sandbox Code Playgroud)
Emi*_*mil 11
Collections.sort(li,new Comparator<Number>() {
@Override
public int compare(Number o1, Number o2) {
Double d1 = (o1 == null) ? Double.POSITIVE_INFINITY : o1.doubleValue();
Double d2 = (o2 == null) ? Double.POSITIVE_INFINITY : o2.doubleValue();
return d1.compareTo(d2);
}
});
Run Code Online (Sandbox Code Playgroud)
看看Andreas_D的 答案进行解释.在上面的代码中,处理所有空值和+无穷大值,使它们移动到最后.
更新1:
由于jarnbjo和aioobe在上面的实现中指出了一个缺陷.所以我认为最好限制Number的实现.
Collections.sort(li, new Comparator<Number>() {
HashSet<Class<? extends Number>> allowedTypes;
{
allowedTypes = new HashSet<Class<? extends Number>>();
allowedTypes.add(Integer.class);
allowedTypes.add(Double.class);
allowedTypes.add(Float.class);
allowedTypes.add(Short.class);
allowedTypes.add(Byte.class);
}
@Override
public int compare(Number o1, Number o2) {
Double d1 = (o1 == null) ? Double.POSITIVE_INFINITY : o1.doubleValue();
Double d2 = (o2 == null) ? Double.POSITIVE_INFINITY : o2.doubleValue();
if (o1 != null && o2 != null) {
if (!(allowedTypes.contains(o1.getClass()) && allowedTypes.contains(o2.getClass()))) {
throw new UnsupportedOperationException("Allowed Types:" + allowedTypes);
}
}
return d1.compareTo(d2);
}
});
Run Code Online (Sandbox Code Playgroud)
更新2:
使用guava的 约束列表(不允许输入null或不支持的类型列表):
List<Number> li = Constraints.constrainedList(new ArrayList<Number>(),
new Constraint<Number>() {
HashSet<Class<? extends Number>> allowedTypes;
{
allowedTypes = new HashSet<Class<? extends Number>>();
allowedTypes.add(Integer.class);
allowedTypes.add(Double.class);
allowedTypes.add(Float.class);
allowedTypes.add(Short.class);
allowedTypes.add(Byte.class);
}
@Override
public Number checkElement(Number arg0) {
if (arg0 != null) {
if (allowedTypes.contains(arg0.getClass())) {
return arg0;
}
}
throw new IllegalArgumentException("Type Not Allowed");
}
}
);
li.add(Double.POSITIVE_INFINITY);
li.add(new Integer(20));
li.add(new Double(12.2));
li.add(new Float(1.2));
li.add(Double.NEGATIVE_INFINITY);
li.add(Float.NEGATIVE_INFINITY);
// li.add(null); //throws exception
// li.add(new BigInteger("22"); //throws exception
li.add(new Integer(20));
System.out.println(li);
Collections.sort(li, new Comparator<Number>() {
@Override
public int compare(Number o1, Number o2) {
Double d1 = o1.doubleValue();
Double d2 = o2.doubleValue();
return d1.compareTo(d2);
}
});
System.out.println(li);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10866 次 |
| 最近记录: |