比较两个对象的字段的字段。

huangapple go评论82阅读模式
英文:

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 &amp; setters
}

Room class has a property roomCapacity:

class Room {
   private int roomCapacity;
   // getters &amp; setters
}

I want to sort House HashMap on the base of Room class property named roomCapacity.

Comparator&lt;House&gt; 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&lt;House&gt; sortByRoomCapacity =
         nullsFirst(comparing(House::getRoom, 
                              comparing(Room::getRoomCapacity, 
                                        nullsFirst(naturalOrder()))));

huangapple
  • 本文由 发表于 2020年4月8日 03:05:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/61087540.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定