java根据一些规则对地图进行排序
我有一张地图,我想根据一些规则对其内容进行排序:
- Sort the map Alphabetically (From A to Z) according to its Values and not its Keys.
- Ignore the Case Sensitivity of the Values while sorting them.
- Put duplicate words into consideration(Words having exact letters Spelling & Case).
- Sort the Alpha numeric words right(Cbc2ee should appear before Cbc100ee).
- Handle non English words(área should appear in the words starting with "a" letter but actually it appears after words starting with "z" letter, considering á another letter).
我想我想要的都是合乎逻辑的。我能够完成第1点、第2点和第3点;3通过此代码:
public <K, V extends Comparable<? super V>> LinkedHashMap<K, V> sortMapByValues( Map<K, V> map ) {
SortedSet<Map.Entry<K, V>> sortedEntries = new TreeSet<Map.Entry<K, V>>(
new Comparator<Map.Entry<K, V>>() {
@Override
public int compare( Map.Entry<K, V> e1, Map.Entry<K, V> e2 ) {
String a = (String)e1.getValue();
String b = (String)e2.getValue();
int diff = a.compareToIgnoreCase( b );
if (diff == 0)
diff = a.compareTo(b);
return diff != 0 ? diff : 1; // Special fix to preserve words with similar spelling.
}
}
);
sortedEntries.addAll( map.entrySet() );
LinkedHashMap<K, V> sortedMap = new LinkedHashMap<K, V>();
for( Map.Entry<K, V> sortedEntry : sortedEntries )
sortedMap.put( sortedEntry.getKey(), sortedEntry.getValue() );
return sortedMap;
}
第(4)点:我找到了它的脚本,但无法将其与代码合并: http://www.davekoelle.com/alphanum.html
第(5)点,我也找到了它的脚本,但我无法将其与我的代码合并: http://www.javapractices.com/topic/TopicAction.do?Id=207
因为这些点会影响比较(…)方法 有人能帮我吗强>
# 1 楼答案
有几点
方法签名应为:
注: -删除与
Comparable
的绑定,因为您正在比较映射值的toString()
,而不是值本身 -根据良好的设计指南,指定抽象类型Map<...>
,而不是具体类型LinkedHashMap
-static
因为它不改变状态-它只是“代码”现在,你的解决方案很好。它只需要多一点代码就可以实现这些额外的点
下面是一些代码,它们可以实现您想要的功能:
以下是测试代码:
输出: