How to create a TreeSet object of any class, sorted by the value of an object variable of this class? For example, there is a class User :

 class User { String name; int age; User(String n, int a) { name = n; age = a; } } 

In the Main class, you need to create a tree of User objects sorted by the variable name How to implement this?

    1 answer 1

     Set<User> users = new TreeSet<>(Comparator.comparing(User::getName)); users.add(new User("Alex", 25)); users.add(new User("Mike", 40)); users.add(new User("Boris", 34)); System.out.println(users); 

    Conclusion:

     [User{name='Alex', age=25}, User{name='Boris', age=34}, User{name='Mike', age=40}] 

    UPD 1 (from comment): in the absence of the getter and provided that the class is package-private and is located in the same package as the calling class:

     Set<User> users = new TreeSet<>(Comparator.comparing(u -> u.name)); 

    UPD 2 (from comment): option without lambda

     Set<User> users = new TreeSet<>(new Comparator<User>() { @Override public int compare(User o1, User o2) { return o1.name.compareTo(o2.name); } }); 
    • The problem is that, following the conditions of the assignment, I cannot make changes to the User class, therefore I cannot implement the getName getter - Vlad Yulin
    • The class User what area of ​​visibility has? - Nikolay
    • Nothing means default - Vlad Yulin
    • located in the same package with main? - Nikolay
    • Yes, in one package - Vlad Yulin