java treemap 重复key_java统计List中的元素重复出现的次数和对map按key或键值排序

package cn.php;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.Comparator;

import java.util.HashMap;

import java.util.HashSet;

import java.util.LinkedHashMap;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.Set;

public class CountList {

public static void main(String[] args) {

List strs = Arrays.asList("a", "b", "c", "d", "e", "a", "a",

"a", "a", "b", "b", "b");

Map map = new HashMap();

Set set = new HashSet(strs);

for (String str : set) {

for (String lstr : strs) {

if (str.equals(lstr)) {

if (map.containsKey(str)) {

Integer count = map.get(str);

count++;

map.put(str, count);

} else {

map.put(str, 1);

}

}

}

}

//printMap(map);

Map sortMap = sortMapByValue(map);

printMap(sortMap);

}

private static Map sortMapByValue(Map map) {

List> mapList = new ArrayList>(

map.entrySet());

Collections.sort(mapList, new Comparator>() {

@Override

public int compare(Entry o1,

Entry o2) {

return o1.getValue()-o2.getValue();

}

});

Map result = new LinkedHashMap();

for(Map.Entry entry:mapList){

result.put(entry.getKey(), entry.getValue());

}

return result;

}

public static void printMap(Map map) {

for (Map.Entry entry : map.entrySet()) {

System.out.println("Key : " + entry.getKey() + " Value : "

+ entry.getValue());

}

}

}

public Map sortMapByKey(Map oriMap) {

if (oriMap == null || oriMap.isEmpty()) {

return null;

}

Map sortedMap = new TreeMap(

new Comparator() {

public int compare(String key1, String key2) {

int intKey1 = 0, intKey2 = 0;

try {

intKey1 = getInt(key1);

intKey2 = getInt(key2);

} catch (Exception e) {

intKey1 = 0;

intKey2 = 0;

}

return intKey1 - intKey2;

}

});

sortedMap.putAll(oriMap);

return sortedMap;

}

private int getInt(String str) {

int i = 0;

try {

Pattern p = Pattern.compile("^\\d+");

Matcher m = p.matcher(str);

if (m.find()) {

i = Integer.valueOf(m.group());

}

} catch (NumberFormatException e) {

e.printStackTrace();

}

return i;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值