我有一个带有三个值(字符串)的ArrayList,但第二个是数字,我希望将数字从0加到例如100.在这个时间它排序1,10,2,21,5等。在输出中我希望有1,2,5,10,21。
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray devices = jsonObj.getJSONArray("list");
for (int i = 0; i < devices.length(); i++) {
JSONObject c = devices.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String known = c.getString("known");
String description = c.getString("description");
String controllerId = c.getString("controllerId");
JSONObject frequencySurvey = c.getJSONObject("frequencySurvey");
if (frequencySurvey.has("5000")) {
JSONObject fivezero = frequencySurvey.getJSONObject("5000");
String timestamp = fivezero.getString("timestamp");
String clients = fivezero.getString("clients");
String enabled = fivezero.getString("enabled");
HashMap<String, String> device = new HashMap<>();
device.put("id", id);
device.put("name", name);
device.put("enabled", enabled);
device.put("clients", clients);
DevicesList.add(device);
}
ListAdapter adapter = new SimpleAdapter(Devices_5_0.this, DevicesList,
R.layout.list_item, new String[]{ "name","clients","enabled"},
new int[]{R.id.name,R.id.clients, enabled});
lv.setAdapter(adapter);
我使用这种类型,但它按字符串排序:
class SortValues implements Comparator {
public int compare(Object obj1, Object obj2) {
HashMap<String, String> test1 = (HashMap<String, String>) obj1;
HashMap<String, String> test2 = (HashMap<String, String>) obj2;
return test1.get("clients").compareTo(test2.get("clients"));
}
}
答案 0 :(得分:0)
如果客户价值是您的数字值,这将起作用:
class SortValues implements Comparator {
public int compare(Object obj1, Object obj2) {
HashMap<String, String> test1 = (HashMap<String, String>) obj1;
HashMap<String, String> test2 = (HashMap<String, String>) obj2;
Long firstClients = Long.valueOf(test1.get("clients"));
Long secondClients = Long.valueOf(test2.get("clients"));
return firstClients.compareTo(secondClients);
}
}
答案 1 :(得分:0)
您可以将数字字符串转换为整数
class SortValues implements Comparator {
public int compare(Object obj1, Object obj2) {
HashMap<String, String> test1 = (HashMap<String, String>) obj1;
HashMap<String, String> test2 = (HashMap<String, String>) obj2;
return new Integer(test1.get("clients"))
.compareTo(new Integer(test2.get("clients")));
}
}
答案 2 :(得分:0)
试试这个:
Collections.sort(arrayList,new ArrayListHashMapComparator());
public class ArrayListHashMapComparator implements Comparator<HashMap<String,String>> {
@Override
public int compare(HashMap<String, String> lhs, HashMap<String, String> rhs) {
try {
return lhs.get(lhs.keySet()).compareToIgnoreCase(rhs.get(rhs.keySet()));
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
}
上面的代码是按升序排序所有hashmap值