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循環?
*我想知道是否有更有效的方法來做到這一點?* - 做*什麼*確切的?此外,您的問題標題最多也不明確。 –
嘗試發表在代碼評論堆棧交易所 –
@JonnyHenly我想知道是否有什麼辦法可以減少上面代碼中for循環的數量? – Irfan