Java: SortedMap, TreeMap, Comparable? How to use?

后端 未结 5 749
别跟我提以往
别跟我提以往 2020-12-06 03:16

I have a list of objects I need to sort according to properties of one of their fields. I\'ve heard that SortedMap and Comparators are the best way to do this.

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 03:41

    You make a Comparator. Then the Comparator compares the field that you want to sort on.

    When you create the TreeMap, you create a TreeMap, and you pass in the Comparator as an argument. Then, as you insert objects of type ClassYouWantToSort, the TreeMap uses your Comparator to sort them properly.

    EDIT: As Adamski notes, you can also make ClassYouWantToSort itself Comparable. The advantage is that you have fewer classes to deal with, the code is simpler, and ClassYouWantToSort gets a convenient default ordering. The disadvantage is that ClassYouWantToSort may not have a single obvious ordering, and so you'll have to implement Comparables for other situations anyway. You also may not be able to change ClassYouWantToSort.

    EDIT2: If you only have a bunch of objects that you're throwing into the collection, and it's not a Map (i.e. it's not a mapping from one set of objects to another) then you want a TreeSet, not a TreeMap.

提交回复
热议问题