关于列表和地图

问题描述:

我在做一个研究让我们说,我有以下数组列表现在关于列表和地图

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,即重复次数是应该是价值和重复的元素是存储为关键请告知如何实现这一点..!

+0

'System.out.println(hm)' – assylias 2012-08-04 17:56:32

+1

请不要编辑你的问题来问一个完全不同的问题。它使答案无用。要将地图打印到控制台,请参阅我以前的评论。 – assylias 2012-08-04 17:58:06

+0

@assylias感谢兄弟它的作品..!但我正在寻找与map.entry man相关的东西.. !! – DON 2012-08-04 17:59:18

你可以简单地遍历列表和:

  • 如果该项目不在地图上,用值= 1
  • 创建它,如果该项目已经在地图,获得的价值,增量递增,并把它放回地图

PS:这是使用泛型好的做法:

List<Integer> list = new ArrayList<Integer>(); 

Map<Integer, Integer> hm = new HashMap<Integer, Integer>(); 
+0

感谢兄弟,能否请您发布更新的代码,这将有助于理解很多..! – DON 2012-08-04 17:29:10

+1

@DON你现在有算法,我建议你根据它编写代码(它不应该超过5行)。如果你有问题,你可以回来问一个关于这个具体问题的问题。 – assylias 2012-08-04 17:30:42

事情是这样的:

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

这听起来像你想有一个Multiset,比如一个在Guava。例如:

Multiset<Integer> multiset = HashMultiset.create(list); 

然后,你可以调用count

System.out.println(multiset.count(1)); // 2 
System.out.println(multiset.count(2)); // 1 
System.out.println(multiset.count(3)); // 2 

不执行Map,不可否认 - 但我怀疑它你需要它的一切。