How to sort child HashMap in object

Viewed 78

I need to implement sorting, but I have problems. I have class User and inside I have HashMap with address. At the moment I don't understanding how to sort child instance with Comparator

Map<String, String> address = new HashMap<>();

address.put("1", "firstAddress");
address.put("2", "secondAddress");
address.put("3", "thirdAddress");

User firstUser = new User(1, "Viktor", "0500000000", address);
User secondUser = new User(2, "Sergey", "0600000000", address);
User thirdUser = new User(3, "Vladimir", "0700000000", address);

List<User> users = new ArrayList<>();

users.add(firstUser);
users.add(secondUser);
users.add(thirdUser);

List<User> sortedUser = users.stream().sorted(user -> {
    return user.getAddress() <-- How to sort address?
}).collect(Collectors.toList());

sortedUser.forEach(System.out::println);
1 Answers

I think this should sort your users by addresses (natural order).

    List<User> sortedUser = users.stream().sorted((user1,user2)-> 
     user1.getAddress().get(user1.getId()).compareTo(user2.getAddress().get(user2.getId()))).collect(Collectors.toList());
Related