-2

I am getting Data from DB in the format List.

UserSession will have WorkStationName, UserName and AreaName.

Now I want to sort it first WorkStationname wise then userName and then AreaName.

How to do it in java? Is it possible to do it using Comparator?

Daniel Larsson
  • 6,278
  • 5
  • 44
  • 82
user223614
  • 303
  • 1
  • 6
  • 15

3 Answers3

1

Best way:

public void sortAccordingToAboveRequirement(List<UserSession> userSessions){

 Collections.sort(userSessions,myComparator);

 }


  static Comparator<UserSession> myComparator=new Comparator<UserSession>() {
    @Override
        public int compare(UserSession user1, UserSession user2) {
        int value=0;
        value=user1.getWorkStationName().compareTo(user2.getWorkStationName())
        if(value!=0) return value;
        value=user1.getUserName().compareTo(user2.getUserName());
        if(value!=0) return value;
        value=user1.getAreaName().compareTo(user2.getAreaName());
        return value;
    }
};

Use compareToIgnoreCase() if you wish :)

Shoaib Chikate
  • 8,665
  • 12
  • 47
  • 70
0

You can use a query to do it.
Or You can override a compare function.
This Post on stackoverflow will help you do that

Community
  • 1
  • 1
pratim_b
  • 1,160
  • 10
  • 29
0

You can use a comparator or you can implement the compareable interface to you class. I give you an example for the secound way:

Collections.sort(UserSessionList);

The class UserSession must implements Comparable<UserSession> now. And then you can override the compareTo method of this class. For example:

@Override
public int compareTo(UserSession o) {

    if(null== o)
        return 1;
    if(getWorkStationName() == null && o.getWorkStationName()==null)
        return 0;
    if(getWorkStationName() == null && o.getWorkStationName()!=null)
        return -1;
    if(getWorkStationName() != null && o.getWorkStationName()==null)
        return 1;
    return o.getWorkStationName().compareTo(getWorkStationName());
}

The rest of the compare function you have to write by your own now! :)

kai
  • 6,702
  • 22
  • 38