简体   繁体   中英

Sort list of strings as BigDecimal in reverse order in Java

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?

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());

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM