2012-08-04 42 views
-1

我在做一個研究讓我們說,我有以下數組列表現在關於列表和地圖

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

回答

3

你可以簡單地遍歷列表和:

  • 如果該項目不在地圖上,用值= 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

0

事情是這樣的:

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

2

這聽起來像你想有一個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,不可否認 - 但我懷疑它你需要它的一切。