关于列表和地图
问题描述:
我在做一个研究让我们说,我有以下数组列表现在关于列表和地图
List list=new ArrayList();
list.add(1);
list.add(1);
list.add(2);
list.add(3);
list.add(3);
,我可以在列表中看到重复的元素是1和3,现在我想创建的HashMap
Map hm = new HashMap();
现在在这个HashMap我想要的键应该是1和3,值应该是2和2,即键1应该有值2,键3应该有值2,即重复次数是应该是价值和重复的元素是存储为关键请告知如何实现这一点..!
答
你可以简单地遍历列表和:
- 如果该项目不在地图上,用值= 1
- 创建它,如果该项目已经在地图,获得的价值,增量递增,并把它放回地图
PS:这是使用泛型好的做法:
List<Integer> list = new ArrayList<Integer>();
和
Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
答
事情是这样的:
Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
for (int i = 0; i < list.size(); ++i)
{
// get a number from the list
int number = list.get(i);
// get the value linked to the key
Integer mapval = hm.get(number);
if (mapval == null)
{
// the value returned is null, which means that the key isn't in the map
// the key wasn't found yet, so the number is zero times in it
mapval = 0;
}
// increase the number of times the number occurs.
hm.put(number, mapval + 1);
}
+0
@Martin谢谢兄弟我更新了帖子..! – DON 2012-08-04 17:53:24
'System.out.println(hm)' – assylias 2012-08-04 17:56:32
请不要编辑你的问题来问一个完全不同的问题。它使答案无用。要将地图打印到控制台,请参阅我以前的评论。 – assylias 2012-08-04 17:58:06
@assylias感谢兄弟它的作品..!但我正在寻找与map.entry man相关的东西.. !! – DON 2012-08-04 17:59:18