您的位置:首页 > 产品设计 > UI/UE

找出一个数组中重复次数最多的字符暨找出Map中的最大Value及其对应的Key

2016-06-15 21:19 801 查看
rt:找出Map中的最大Value及其对应的Key,常用于找出一个数组中重复次数最多的字符
import java.util.*;
public class KeyOnMaxValue{
public static void main(String[] args) {
Map<Integer, Integer> mp = new HashMap<Integer, Integer>();
int maxKey = 0;
int maxValue = 0;
mp.put(2, 13);
mp.put(3, 14);
mp.put(4, 10);
Iterator it = mp.entrySet().iterator();// 将mp的键值对通过迭代器赋给it
while (it.hasNext()) {// 当it不为空的时候,将it赋给Map。Entry型的对象e
Map.Entry<Integer, Integer> e = (Map.Entry) it.next();
if (e.getValue() > maxValue) {// 当前e的value大于maxValue时
maxValue = e.getValue();
maxKey = e.getKey();
}
}
System.out.println(maxKey + " " + maxValue);// 打印出最大的Value对应的Key和Value值
}
}

输出:

3 14
找出一个数组中出现最多次数的字符:
import java.util.*;

public class Inputmany {
public static void max(Map<Character, Integer> mp) {
char maxKey = '#';
int maxValue = 0;
Iterator it = mp.entrySet().iterator();// 将mp的键值对通过迭代器赋给it////////
while (it.hasNext()) {// 当it不为空的时候,将it赋给Map。Entry型的对象e///////
Map.Entry<Character, Integer> e = (Map.Entry) it.next();////////
if (e.getValue() > maxValue) {// 当前e的value大于maxValue时
maxValue = e.getValue();
maxKey = e.getKey();
}
}
System.out.println(maxKey + " " + maxValue);// 打印出最大的Value对应的Key和Value值
}
public static void main(String[] args) {
char[] array = { 'a', 's', 'd', 'f', 'a', 'a' };
Map mp = new HashMap();
for (int i = 0; i < array.length; i++) {
if (mp.containsKey(array[i])) {
mp.put(array[i], (int) mp.get(array[i]) + 1);
} else {
mp.put(array[i], 1);
}
}
max(mp);
}
}
输出:
a 3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: