Home > other >  Sort list of strings as BigDecimal in reverse order in Java
Sort list of strings as BigDecimal in reverse order in Java

Time:12-20

I need to sort list of strings comparing them as BigDecimal. Here is what I tried:

List<String> sortedStrings = strings
    .stream()
    .sorted(Comparator.reverseOrder(Comparator.comparing(s -> new BigDecimal(s))))
    .collect(Collectors.toList());
List<String> sortedStrings = strings
    .stream()
    .sorted(Comparator.reverseOrder(Comparator.comparing(BigDecimal::new)))
    .collect(Collectors.toList());
List<String> sortedStrings = strings
    .stream()
    .sorted(Comparator.comparing(BigDecimal::new).reversed())
    .collect(Collectors.toList());

Can I somehow do this without explicitly specifying the types?

CodePudding user response:

You can do it like this.

List<String> strings = List.of("123.33", "332.33");
List<String> sortedStrings = strings
        .stream()
        .sorted(Comparator.comparing(BigDecimal::new, Comparator.reverseOrder()))
        .collect(Collectors.toList());

System.out.println(sortedStrings);

prints

[332.33, 123.33]

You could also do it like this but need to declare the type parameter as a String.

List<String> sortedStrings = strings
        .stream()
        .sorted(Comparator.comparing((String p)->new BigDecimal(p)).reversed())
        .collect(Collectors.toList());

But here is the way I would recommend doing it. BigDecimal implements the Comparable interface. So you simply map all the values to BigDecimal, sort them in reverse order, and then convert back to a String. Otherwise, the other solutions will continue to instantiate a BigDecimal object just for sorting and that could result in many instantiations.

List<String> sortedStrings = strings
        .stream()
        .map(BigDecimal::new)
        .sorted(Comparator.reverseOrder())
        .map(BigDecimal::toString)
        .collect(Collectors.toList());

System.out.println(sortedStrings);

CodePudding user response:

If you want a function that can sort anything by converting it to another class you should just have the following sortWithConverter function

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

class Main {
    static public <T, U extends Comparable<? super U>> List<T> sortWithConverter(List<T> unsorted, Function<T, U> converter) {
        return unsorted
            .stream()
            .sorted(Comparator.comparing(converter).reversed())
            .collect(Collectors.toList());
    }

    public static void main(String[] args) {
        List<String> strings = new ArrayList<>();
        strings.add("5");
        strings.add("1");
        strings.add("2");
        strings.add("7");
        System.out.println(sortWithConverter(strings, BigDecimal::new));
    }
}

This program prints: [7, 5, 2, 1]

  •  Tags:  
  • java
  • Related