Reputation: 2973
I have a Java
class named Friend
public class Friend {
public String friendsUserName;
public boolean isFavorite;
public boolean isFriend;
}
I get Json
file from the server containing JsonArray
of this class Friend
. I use Gson
class to parse and map the Json
to the ArrayList<Friend>
.I have to sort the array in following manner
Friend
who are isFavorite
and isFriend
ArrayList
contains remaining Friend
who are only isFriend
ArrayList
contains Friend
where isFriend
is False
.So for that I can use the method described on this ComparatorChain
Or I can use the following way to properly sort the ArrayList<Friend>
public ArrayList<Friend> friendsList;
public void sortArrayList() {
ArrayList<Friend> favoriteList = new ArrayList<Friend>();
ArrayList<Friend> friendOnlyList = new ArrayList<Friend>();
ArrayList<Friend> nonFriendList = new ArrayList<Friend>();
for (int length = friendsList.size(), i = length - 1; i >= 0; i--) {
Friend friend = friendsList.get(i);
if (friend.isFriend) {
if (friend.isFavorite) {
favoriteList.add(friend);
} else {
friendOnlyList.add(friend);
}
} else {
nonFriendList.add(friend);
}
friendsList.remove(i);
}
addAllAndClear(favoriteList);
favoriteList = null;
addAllAndClear(friendOnlyList);
friendOnlyList = null;
addAllAndClear(nonFriendList);
nonFriendList = null;
}
public void addAllAndClear(ArrayList<Friend> updatedList) {
Collections.sort(updatedList, nameComparator);
friendsList.addAll(updatedList);
updatedList.clear();
updatedList = null;
}
Comparator<Friend> nameComparator = new Comparator<FriendListResponse.Friend>() {
@Override
public int compare(Friend lhs, Friend rhs) {
return lhs.friendsUserName.compareTo(rhs.friendsUserName);
};
};
Efficiency
wise which should I follow the ComparatorChain
or my own method. I am developing this for Android
platform,so Memory Management
and Efficiency
is of topmost priority.
P.S. I am no good at using tools to compare Efficiency
.
Upvotes: 0
Views: 145
Reputation: 993
In your class Friend implement Comparable interface and then use Collections.sort()
Or as @vipul mittal suggest
Comparator may look like
Comparator<Friend> favoriteComparator = new Comparator<FriendListResponse.Friend>() {
@Override
public int compare(Friend lhs, Friend rhs) {
int i=0,j=0;
if(lhs.isFavorite() && lhs.isFriend())
i++;
if(lhs.isFriend())
i++;
if(rhs.isFavorite() && rhs.isFriend())
j++;
if(rhs.isFriend())
j++;
if (i==j) {
return lhs.friendsUserName.compareTo(rhs.friendsUserName);
}
else {
return i-j;
}
};
};
Upvotes: 2
Reputation: 17401
Try following comparator:
Comparator<Friend> favoriteComparator = new Comparator<FriendListResponse.Friend>() {
@Override
public int compare(Friend lhs, Friend rhs) {
int i=0,j=0;
if(lhs.isFavorite()&&lhs.isFriend())
i++;
if(lhs.isFriend())
i++;
if(rhs.isFavorite()&&rhs.isFriend())
j++;
if(rhs.isFriend())
j++;
return i-j;
};
};
While sorting:
Collections.sort(friendsList,favoriteComparator);
Upvotes: 2