[Solved] Sort a class array by a string attribute in Java


For Java 8 use a lambda expression and the Arrays sort function:

Users[] someUsers = {user1, user2, user3};
Arrays.sort(someUsers, (a,b) -> a.firstName.compareTo(b.firstName));

For previous versions use a Collection Comparator:

Users[] someUsers = {user1, user2, user3};
List<Users> userList = new ArrayList<Users>(Arrays.asList(someUsers));
Comparator<Users> comparator = new Comparator<Users>() {
    @Override
    public int compare(Users left, Users right) {
        return left.firstName.compareTo(right.firstName);
    }
};
Collections.sort(userList, comparator);

2

solved Sort a class array by a string attribute in Java