java计算问题关于List和map
public static int maxcount(list){
//这里面怎么写呀。要用到map
}
比如
[1,1,2,3,4] 返回2
[5,6,5,6,5,6]返回3
[0.0.0.0.0]返回5
谢谢各位了 展开
public static int maxcount(List<Integer> list) {
Map<Integer, Integer> map = new HashMap();
for (Integer temp : list) {//遍历每个值出现的次数
Integer count = (Integer) map.get(temp);
map.put(temp, (count == null) ? 1 : count + 1);
}
SortedMap<Integer, Integer> treeMap = new TreeMap(map);//排序
return treeMap.get(treeMap.firstKey());//输出最大的值
}
public static void main(String[] args)
{
System.out.println(maxcount(arrayToList(new int[]{1,1,2,3,4})));
System.out.println(maxcount(arrayToList(new int[]{5,6,5,6,5,6})));
System.out.println(maxcount(arrayToList(new int[]{0,0,0,0,0})));
}
public static int maxcount(List<? extends Object> list)
{
Map<String, List<Object>> map = new HashMap<String, List<Object>>();
for (Object object : list)
{
if (!map.containsKey(object.toString()))
{
map.put(object.toString(), new ArrayList<Object>());
}
map.get(object.toString()).add(object);
}
int max = 0;
for (List<Object> objects : map.values())
{
if (max < objects.size())
{
max = objects.size();
}
}
return max;
}
private static List<Integer> arrayToList(int[] array)
{
List<Integer> list = new ArrayList<Integer>();
for (int i : array)
{
list.add(i);
}
return list;
}
2014-03-13
int max=-1;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(Integer i : list){
if(map.containsKey(i)){
int v=map.get(i)+1;
map.put(i, v);
if(v>max){
max=v;
}
}else{
map.put(i, 1);
}
}
return max;
}
楼主,试试吧