排序列表&LT;&GT;通过数值 [英] Sorting List<> by numeric value
问题描述
我有一个公开名单&LT; FriendProfile&GT;朋友=新的ArrayList&LT; FriendProfile&GT;();
。我通过读取服务器的信息初始化好友列表。该FriendProfile对象包含一个名为INT 私人诠释userPosition;
I've got a public List<FriendProfile> friends = new ArrayList<FriendProfile>();
. I initialize the friends list by reading the information from the server. The FriendProfile object contains a int called private int userPosition;
在好友列表中已被初始化,我想有与FriendProfile对象进行排序的好友列表中的最高 userPosition
在列表索引0,然后排序通过相应地,索引1次高 userPosition
...
Once the friends list has been initialized, I would like to sort the friends list by having the FriendProfile object with the highest userPosition
at index 0 of the list and then sort by accordingly, index 1 with the second highest userPosition
...
我想我可以写一个排序算法,但我正在寻找prewritten code(也许是JDK有一些方法来提供?)
I guess I could write an sorting algorithm, yet I'm looking for prewritten code (maybe the JDK has some methods to offer?)
帮助是AP preciated!
Help is appreciated!
推荐答案
使用 Collections.sort()
并指定比较
:
Collections.sort(friends,
new Comparator<FriendProfile>()
{
public int compare(FriendProfile o1,
FriendProfile o2)
{
if (o1.getUserPosition() ==
o2.getUserPosition())
{
return 0;
}
else if (o1.getUserPosition() <
o2.getUserPosition())
{
return -1;
}
return 1;
}
});
或者 FriendProfile
实施可比&LT; FriendProfile方式&gt;
这篇关于排序列表&LT;&GT;通过数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!