本帖最后由 李知伦 于 2012-8-22 17:41 编辑
HashMap取出元素时,能否控制顺序
比如取字母出现次数,能否按照,原始字符串的排列顺序,升序,降序等
- import java.util.HashMap;
- import java.util.Map;
- public class getCharTimes {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- String str = "sdfasdewefqmcoad";
- String character = "";
- int frequency = 0;
- Map<String, Integer> map = new HashMap<String, Integer>();
- for (int i=0; i < str.length(); i++) {
- String key = str.substring(i, i+1);
- if (map.containsKey(key)) {
- map.put(key, map.get(key)+1);
- }
- else {
- map.put(key, 1);
- }
- }
- for (Map.Entry<String, Integer> m : map.entrySet()) {
- //取得最终的Key,value
- character = m.getKey();
- frequency = m.getValue();
- System.out.println(character + "(" + frequency + ")");
- }
- }
- }
|
|