Java BigDecimal

  • + 1 comment

    For sure -

    Arrays.sort takes an array and a Comparator. We pass in the array x, and

    Collections.reverseOrder(Comparator.comparing(BigDecimal::new))
    

    Collections.reverseOrder does exactly what it says, returns the Comparator that is passed in which performs its operation in reverse.

    Comparator.comparing takes a function to use for the actual comparison and returns a Comparator.

    In our case we want to compare BigDecimals so we can pass in a method reference which invokes BigDecimal's String constructor. This is the same as saying:

    Comparator.comparing(y -> new BigDecimal(y))
    

    Since we converted from String to BigDecimal using this constructor the comparator will now use BigDecimal's compareTo method to sort the Array.