2013-04-24 43 views
0

我有一個ArrayList的URL作爲它的字符串。我想查找不同主機網站的列表以及顯示的次數。 例如,如果在我的列表中有5個鏈接到谷歌我想統計他們全部。我是通過列表中的每個URL開始一個循環迭代:如何從java中的urls數組列表中獲取主機站點列表和每個主機實例?

for(int i = 0;i<list.size(); i++){ 

    //for every url at i identify the host site and put in hashmap where the key is the 
    //host site and the variable is the number of URL's from that host 
    } 

我怎麼會從指定URL字符串的URL的主機(如google.com)。我不知道如何編碼那部分。

回答

3

類似的東西(未經測試,但原理是有效的)?

Map<String, Integer> map = new HashMap<String, Integer>(); 
    for(int i = 0;i<list.size(); i++) 
    { 
     URL url = new URL(list[i]); 
     if (map.containsKey(url.getHost())) 
     { 
      map.put(url.getHost(), map.get(url.getHost()) + 1); 
     } 
     else 
     { 
      map.put(url.getHost(), 1); 
     } 
    } 

如果您想打印出的哈希地圖:

for (Map.Entry entry : map.entrySet()) 
    { 
     System.out.println(entry.getKey() + " " + entry.getValue()); 
    } 
+0

只是好奇,我會打印出散列表內容。我正在嘗試,但似乎無法正確執行。謝謝btw – user1835504 2013-04-24 18:08:56

+1

@ user1835504只是編輯我的答案,打印出散列表。 – TheEwook 2013-04-24 18:14:03

1

我建議您使用URL.getHost()來檢索主機名稱,並使用Map<String,Integer>來存儲您看到的每個主機的計數。

+0

謝謝,我會給一個嘗試。 – user1835504 2013-04-24 15:13:33

1

創建URL對象(它有臨危一個String構造函數),並使用它和getHost()方法

相關問題