【发布时间】:2016-08-16 23:28:01
【问题描述】:
我正在尝试根据用户的直接朋友为他们推荐朋友,并根据他们的频率(即推荐的朋友出现在用户的直接朋友列表中的次数)对他们进行排名。下面是解决问题的工作代码。
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循环?
【问题讨论】:
-
我想知道是否有更有效的方法来做到这一点? — 究竟要做什么?此外,您的问题的标题充其量是模棱两可的。
-
尝试在 Code Review Stack Exchange 上发帖
-
@JonnyHenly 我想知道是否有什么方法可以减少上述代码中的 for 循环数?
-
OFFTOPIC 但总是使用最易读的方式,而不是最有效的方式,而且它总是以良好的性能得到回报。
标签: java data-structures collections time-complexity