[英]Sorting Custom Object Price Values in Ascending and Descending order
I have Price Values like below in String format getting from Custom object 我有以下价格格式的字符串格式,从“自定义”对象获取
2,000,3,000,5,000,300,-,600,-,507,- 2,000,3,000,5,000,300,-,600,-,507,-
I want to Sort the above Price Values in Ascending and Descending order 我想按升序和降序对上述价格值进行排序
Could any one help? 有谁可以帮忙吗?
I have tried this: 我已经试过了:
Comparator<Cars> comparator = new Comparator<Cars>() {
@Override
public int compare(Cars object1, Cars object2) {
// return Float.compare(Integer.parseInt(object1.getPrice()), Integer.parseInt(object2.getPrice()));
String price1=object1.getPrice().replaceAll(",","");
price1=price1.replaceAll("-","");
String price2=object2.getPrice().replaceAll(",","");
price2=price2.replaceAll("-","");
return ((Integer)Integer.parseInt(price1)).compareTo((Integer)Integer.parseInt(price2));
}
};
But if i execute the statement 但是如果我执行语句
Collections.sort(carsList, comparator); Collections.sort(carsList,比较器);
getting the Exception 得到例外
Exception: Error:java.lang.NumberFormatException: Invalid int: ""
异常:
Error:java.lang.NumberFormatException: Invalid int: ""
Error:java.lang.NumberFormatException: Invalid int: ""
错误:java.lang.NumberFormatException:无效的int:“”
is happening because of "-" elements in your array. 由于数组中的“-”元素而发生。 And when you do this:
当您这样做时:
price1=price1.replaceAll("-","");
the new price1 string contains an empty string "" 新的price1字符串包含一个空字符串“”
leading the following Integer.parseInt
statement to fail with NumberFormatExcpetion
. 导致以下
Integer.parseInt
语句因NumberFormatExcpetion
而失败。
As parsetInt
cannot convert an empty string to number. 由于
parsetInt
无法将空字符串转换为数字。
So one solution is either remove such elements from the array. 因此,一种解决方案是从阵列中删除此类元素。
Or other solution is define a default values integer for empty string. 或其他解决方案是为空字符串定义默认值整数。 Something like:
就像是:
price1=price1.replaceAll("-","");
if("".equals(price1))
price1="0";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.