英文:
Compare two objects by their field's field
问题
我有一个名为House的类,它具有类型为Room
的属性。
class House {
private Room room;
// 获取器和设置器
}
Room
类有一个名为roomCapacity
的属性:
class Room {
private int roomCapacity;
// 获取器和设置器
}
我想要根据Room类的名为roomCapacity的属性对House HashMap进行排序。
Comparator<House> sortByRoomCapacity =
Comparator.nullsFirst(Comparator.comparing(House::getRoom,
Comparator.nullsFirst(Comparator.naturalOrder())));
但是目前我无法访问获取Room类属性House::getRoomCapacity
。
英文:
I have a class named House and it has property of type Room
.
class House {
private Room room;
// getters & setters
}
Room
class has a property roomCapacity
:
class Room {
private int roomCapacity;
// getters & setters
}
I want to sort House HashMap on the base of Room class property named roomCapacity.
Comparator<House> sortByRoomCapacity =
Comparator.nullsFirst(Comparator.comparing(House::getRoom,
Comparator.nullsFirst(Comparator.naturalOrder())));
But for now I am inaccessible to get this property(getRoomCapacity) of Room class House::getRoom
答案1
得分: 3
你就快完成了。
再加一个嵌套的 comparing
方法就可以了:
Comparator<House> sortByRoomCapacity =
nullsFirst(comparing(House::getRoom,
comparing(Room::getRoomCapacity,
nullsFirst(naturalOrder()))));
英文:
You're almost there.
One more nested comparing
method should do the trick:
Comparator<House> sortByRoomCapacity =
nullsFirst(comparing(House::getRoom,
comparing(Room::getRoomCapacity,
nullsFirst(naturalOrder()))));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论