sort arraylist of complex objects alphabetically

前端 未结 2 823
南旧
南旧 2021-02-09 02:16

I know that Collections.sort(myArrayList) can sort an arraylist alphabetically when they are strings, but what about when they are something more complex such as a

相关标签:
2条回答
  • 2021-02-09 03:00

    I would create an inner class implementing the Comparator interface:

    public class Car {
    public double horsePower;
    
    class CarHorsePowerComparator implements Comparator<Car> {
        @Override
        public int compare(Car car1, Car car2) {
            return Integer.valueOf(car.horsePower).compareTo(Integer.valueOf(car2.horsePower))          }
        }
    }
    

    Now when you want to sort your Car list by horsePower:

    List<Car> list = new ArrayList<Car>(myCars); //your Car list
    Collections.sort(list, new CarHorsePowerComparator());
    
    0 讨论(0)
  • 2021-02-09 03:21

    Use the function taking as second parameter a Comparator.

    Il allows you to pass an instance of Comparator to sort according to your needs. Note that the javadoc of Comparator contains guidelines regarding the building of comparators.

    You may define the comparator as an anonymous class if it's only locally used. Here's an example where I sort objects regarding to one of their fields which is a String :

    Collections.sort(groupResults, new Comparator<ProductSearchResult>() {
        public int compare(ProductSearchResult result1, ProductSearchResult result2) {
            return result1.product.getRsId().compareTo(result2.product.getRsId());
        }
    });
    

    Alternatively, you might also make your class implement the Comparable interface but this makes sense only if you can define a natural (obvious) order.

    0 讨论(0)
提交回复
热议问题