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); } });