java中Map排序问题
按key排序
public class MapSortDemo {
public static void main(
String[] args) {
Map<
String,
String> map =
new TreeMap<
String,
String>();
map.put(
"KFC",
"kfc");
map.put(
"WNBA",
"wnba");
map.put(
"NBA",
"nba");
map.put(
"CBA",
"cba");
Map<
String,
String> resultMap = sortMapByKey(map);
for (Map.Entry<
String,
String> entry : resultMap.entrySet()) {
System.out.println(entry.getKey() +
" " + entry.getValue());
}
}
public static Map<
String,
String> sortMapByKey(Map<
String,
String> map) {
if (map ==
null || map.
isEmpty()) {
return
null;
}
Map<
String,
String> sortMap =
new TreeMap<
String,
String>(
new MapKeyComparator());
sortMap.putAll(map);
return sortMap;
}
}
class MapKeyComparator implements Comparator<
String>{
@Override
public int compare(
String str1,
String str2) {
return str1.compareTo(str2);
}
}
按value排序
public class Main {
public static void main(String[] args) {
Scanner sc =
new Scanner(System.
in);
while(sc.hasNext()){
Map<Character, Integer> map =
new LinkedHashMap<>();
String sentence = sc.nextLine();
char[] arr = sentence.toCharArray();
for(
int i=
0;i<arr.length;i++){
if((arr[i] >=
'A' && arr[i] <=
'Z') ||
(arr[i] >=
'a' && arr[i] <=
'z')||
arr[i] >=
'1' && arr[i] <=
'9' ||
arr[i]==
' '){
if(map.
get(arr[i]) !=
null){
map.put(arr[i], map.
get(arr[i])+
1);
}
else{
map.put(arr[i],
1);
}
}
}
List<Map.Entry<Character, Integer>> entryList =
new ArrayList<Map.Entry<Character, Integer>>(
map.entrySet());
Collections.sort(entryList,
new MapValueComparator());
for (Map.Entry<Character, Integer> cc : entryList) {
System.
out.print(cc.getKey());
}
}
}
private static class MapValueComparator implements Comparator<Map.Entry<Character, Integer>>{
@Override
public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
if(o1.getValue() < o2.getValue())
return 1;
else if(o1.getValue() == o2.getValue())
return o1.getKey()-(o2.getKey());
else
return -
1;
}
}
}
转载请注明原文地址: https://ju.6miu.com/read-668038.html