Sorting as a child of ArrayList

my professor tasked me with sorting a SoftDrinkList Class that extends to ArrayList of SoftDrinks in both ascending and descending order but I can't seems to get it to work

private void sort(boolean isAscending){
    if (isAscending){
        Collections.sort(super(),Collections.reverseOrder((a,b) -> {
        return a.getPrice().compareTo(b.getPrice());
    }));
    }
}

I am quite new to Java so I don't really know the inner working of its, any help would be appreciated. PS: is there any way to create a temporary sorted ArrayList from the current one? As I only need to print in sorted order, I don't really want to sort the actual array. Thanks

1 answer

  • answered 2019-12-15 03:11 Christilyn Arjona

    You can modify your function to return a sorted copy of the original list. Assuming you're using a class called SoftDrink, you can do:

     private ArrayList<SoftDrink> sort(boolean isAscending){
        ArrayList<SoftDrink> copy = new ArrayList<>(originalList); // creates a copy of your original list
        Comparator<SoftDrink> ascendingComparator = new Comparator<SoftDrink>() {
            @Override
            public int compare(SoftDrink a, SoftDrink b) {
                return a.getPrice() - b.getPrice();
            }
        };
        if (isAscending) {
            copy.sort(ascendingComparator);
        } else {
            copy.sort(Collections.reverseOrder(ascendingComparator));
        }
    
        return copy;
    }