2016-08-16 62 views
2

我試圖根據他們的直接朋友爲用戶推薦朋友推薦,並根據他們的頻率對他們進行排名(即推薦朋友出現在用戶的直接朋友列表中的次數)。以下是解決問題的工作代碼。在下面的代碼中減少循環

public List<String> getFriendsRecommendations(String user) 
{ 
    Recommendations rd = new Recommendations(); 
    List<String> result= new ArrayList<String>(); 

    List<String> drfriend = rd.getdirectfriends(user); //return list of direct friend for the user. 

    List<ArrayList<String>> allfriends = new ArrayList<ArrayList<String>>(); 
    Map<String, Integer> mapfriend = new HashMap<String, Integer>(); 

    List<String> userfriend = rd.getfriends(user); //returns the list of all the friends for a given user. 

    int counter =0; 
    for(String s: drfriend) 
    { 
     allfriends.add(new ArrayList<String>(rd.getfriends(s))); 
     rd.intersection(userfriend, allfriends.get(counter), mapfriend); 
     counter++; 

    } 
    result.addAll(mapfriend.keySet()); 

    //Sorting based on the value of hashmap. friend with highest value will be recommended first 
    Collections.sort(result, new Comparator<String>(){ 
     public int compare(String s1, String s2) 
     { 
      if(mapfriend.get(s1) > mapfriend.get(s2)) 
       return -1; 
      else if(mapfriend.get(s1) < mapfriend.get(s2)) 
       return 1; 
      else if(mapfriend.get(s1) == mapfriend.get(s2)) 
      { 
       return s1.compareTo(s2); 
      } 
      return 0; 
     } 
    }); 


    return result; 
} 

public void intersection(List<String> lt1, ArrayList<String> lt2, Map<String, Integer> ranked) 
{ 
    lt2.removeAll(lt1); // ignoring the friends that user is already connected to 

    for(String st: lt2) 
    { 
     boolean val = ranked.containsKey(st); 
     if(val) 
     { 
      int getval = ranked.get(st); 

      ranked.put(st, getval+1); //friend name as a key and the value would be the count. 
     } 
     else 
     { 
      ranked.put(st, 1); 
     } 
    } 
} 

我想知道是否有更有效的方法來解決上述問題而不是使用2 for循環?

+2

*我想知道是否有更有效的方法來做到這一點?* - 做*什麼*確切的?此外,您的問題標題最多也不明確。 –

+0

嘗試發表在代碼評論堆棧交易所 –

+0

@JonnyHenly我想知道是否有什麼辦法可以減少上面代碼中for循環的數量? – Irfan

回答

1

比較器的快速提示:獲取您在開始比較時感興趣的兩個值,並將它們存儲在變量中,這樣您在當前最差情況下只能執行2次獲取調用的最大值,而不是6次得到調用會散列字符串,所以更少更好)。

至於簡化for循環,你可以得到一個朋友的朋友列表,並計算每個朋友在該列表中的發生?然後,刪除任何你已經與朋友在一起的朋友。

+0

感謝您的快速提示 – Irfan