我有class DBManager
{
protected $adapter ;
protected $connection ;
/**
* Constructor
*/
public function __construct()
{
$configs = array(
'hostname' => DB_SERVER_NAME,
'driver' => 'Pdo_Mysql',
'database' => DB_DATABASE_NAME,
'username' => DB_USER_NAME,
'password' => DB_PASSWORD ,
);
$this->adapter = new Adapter($configs);
}
}
,其中包含一些ArrayList
。每个HashMap<String,String>
包含两对数字和两对名称,所有这些都是字符串格式。就像这样:
HashMap
。
我希望按此规则对h1:<"num1","20"> <"num2","17"> <"name1","x"> <"name2","y">
进行排序:
ArrayList
如果他们(h1.num1 + h1.num2) > (h2.num1 + h2.num2)
将仅适用于equal then comparison
。
但由于(h1.num1 > h2.num1)
和num1
是字符串,我无法进行此类比较。顺便说一句,如果我把它们转换为int,那么我面临一般错误。最后,如果我删除通用,
我在return语句中遇到语法错误:num2
有什么想法吗?
在下面的代码中,错误位于cannot cast from File to int.
语句:
return
答案 0 :(得分:0)
使用自定义Comparator
实现并将您的逻辑放在compareTo()
中以对哈希图进行排序。
至于你的第二部分,字符串有一个compareTo()
,可以让你比较一个字符串。
答案 1 :(得分:0)
编辑下面的代码解决了我的问题:
Collections.sort(mediaStatsDetailsArrayList, new Comparator <HashMap<String, String>>() {
@Override
public int compare(HashMap h1, HashMap h2) {
int likes1 = Integer.parseInt((String) h1.get("noOfLikes"));
int sum1 = (Integer.parseInt((String) h1.get("noOfLikes")) + Integer.parseInt((String) h1.get("noOfComments")));
h1.put("likes", likes1);
h1.put("sum", sum1);
int likes2 = Integer.parseInt((String) h2.get("noOfLikes"));
int sum2 = (Integer.parseInt((String) h2.get("noOfLikes")) + Integer.parseInt((String) h2.get("noOfComments")));
h2.put("likes", likes2);
h2.put("sum", sum2);
if (sum1 == sum2)
return ((Integer) h1.get("likes")).compareTo((Integer) h2.get("likes"));
return ((Integer) h1.get("sum")).compareTo((Integer) h2.get("sum"));
}
});
答案 2 :(得分:0)
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put("num1", "\"20\"");
hmap.put("num2", "17");
hmap.put("name1", "\"x\"");
hmap.put("name2", "y");
System.out.println("Before Sorting:");
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry me = (Map.Entry)iterator.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
Map<Integer, String> map = new TreeMap<Integer, String>(hmap);
System.out.println("After Sorting:");
Set set2 = map.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry me2 = (Map.Entry)iterator2.next();
System.out.print(me2.getKey() + ": ");
System.out.println(me2.getValue());
}