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?
Advertisement
Answer
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);