[英]Java Sorting Price Values Ascending and Descending
I have the price Values in String format ("2,000","3,000" etc) 我有String格式的价格值(“ 2,000”,“ 3,000”等)
I want to Sort the Price Values 我要对价格值进行排序
for that I have used the Below Code: 为此,我使用了以下代码:
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()));
return ((Integer)Integer.parseInt(object1.getPrice())).compareTo((Integer)Integer.parseInt( object2.getPrice()));
}
If i execute the Below Statement 如果我执行以下语句
Collections.sort(carsList, comparator);
I'm getting 我越来越
Error: java.lang.NumberFormatException: Invalid int: "3,000"
Could any one help? 有谁可以帮忙吗?
Integer.parseInt()
will not work with currency containing commas( ,
). Integer.parseInt()
不适用于包含逗号( ,
)的货币。 You may have to do the string manipulation to remove the comma before trying to use the parseInt()
method. 在尝试使用
parseInt()
方法之前,您可能必须进行字符串操作以删除逗号。
Doing something like this: 做这样的事情:
String obj1Price = object1.getPrice().replaceAll(",","");
String obj2Price = object2.getPrice().replaceAll(",","");
return ((Integer)Integer.parseInt(obj1Price )).compareTo((Integer)Integer.parseInt( obj2Price)));
在将货币数据(字符串表示形式)传递给您的方法之前,对其进行修改,例如,您可以使用以下方法:
"2,000".replaceAll(",","");
Try this 尝试这个
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String object1, String object2) {
int i = 0;
int j = 0;
try {
i = NumberFormat.getNumberInstance(java.util.Locale.US).parse(object1).intValue();
j = NumberFormat.getNumberInstance(java.util.Locale.US).parse(object2).intValue();
} catch (ParseException e) {
}
// return Float.compare(Integer.parseInt(object1.getPrice()), Integer.parseInt(object2.getPrice()));
System.out.println("i = " + ((Integer)i) + " , j = " + ((Integer)j));
return ((Integer)i).compareTo(((Integer)j));
}
};
System.out.println("xxxxxxxxx = " + comparator.compare("4,000", "3,000"));
return ((Integer)Integer.parseInt(obj1Price.replaceAll(",","") )).compareTo((Integer)Integer.parseInt( obj2Price.replaceAll(",",""))));
将工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.