How to sort a List<Object> alphabetically using Object name field

后端 未结 16 1448
暗喜
暗喜 2020-11-28 06:00

I have a List of Objects like List p.I want to sort this list alphabetically using Object name field. Object contains 10 field and name field is o
16条回答
  •  萌比男神i
    2020-11-28 06:03

    If your objects has some common ancestor [let it be T] you should use List instead of List, and implement a Comparator for this T, using the name field.

    If you don't have a common ancestor, you can implement a Comperator, and use reflection to extract the name, Note that it is unsafe, unsuggested, and suffers from bad performance to use reflection, but it allows you to access a field name without knowing anything about the actual type of the object [besides the fact that it has a field with the relevant name]

    In both cases, you should use Collections.sort() to sort.

    提交回复
    热议问题