-3

I am generating the .txt file from beanshell scripting. Now I am having problem for sorting. If anyone can give any idea that will be great help. The file looks like:

UserId FirstName LastName  Status     roleId
2025    A           B       Active     3
2021    C           D       InActive   2
2036    E           F       Active     1
3012    G           H       Active     2
5012    I           J       InActive   1

Sorting should be done by while writing file by Status in ascending order, then by roleId in ascending order, then by UserId in ascending order.

  • 1
    Sorting should have nothing to do with the text file. You should be sorting the list _before_ generating the text file. I'm assuming you're using a `List`, so you can use `Collections.sort(list, comparator)`, where `comparator` is a custom comparator that controls how the items are intended to be sorted by defining what makes one item "bigger" or "smaller" than another item. See [here](https://stackoverflow.com/questions/5245093/how-do-i-use-comparator-to-define-a-custom-sort-order) for more info. – Jordan Feb 04 '20 at 21:33

1 Answers1

0

Assuming


public class User {

    private Integer userId;
    private String firstName, lastName;
    public enum Status{
        ACTIVE, INACTIVE;
    }
    private Status status;
    private Integer roleId;

     // getter and setter
}

You can use a comparator like this:


public class UserComparator implements Comparator<User> {

    @Override
    public int compare(User o1, User o2) {

    @Override
    public int compare(User o1, User o2) {
        int bystatus = o1.getStatus().compareTo(o2.getStatus());
        if (bystatus != 0) {
            return bystatus;
        }
        int byid = o1.getUserId().compareTo(o2.getUserId());
        if (byid != 0) {
            return byid;
        }
        return o1.getRoleId().compareTo(o2.getRoleId());
    }

}

Finally:

Collections.sort(list, comparator);
Renato
  • 2,077
  • 1
  • 11
  • 22