在Java中,按相反的顺序将字符串列表排序为BigDecimal



我需要对字符串列表进行排序,将它们作为BigDecimal进行比较。以下是我尝试过的:

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

我可以在不明确指定类型的情况下以某种方式做到这一点吗?

您可以这样做。

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

打印

[332.33, 123.33]

您也可以这样做,但需要将类型参数声明为String。

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

但我建议这样做。BigDecimal实现了Comparable接口。因此,您只需将所有值映射到BigDecimal,按相反的顺序对它们进行排序,然后转换回String。否则,其他解决方案将继续实例化BigDecimal对象,仅用于排序,这可能会导致多次实例化。

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

如果你想要一个函数,可以通过将其转换为另一个类来对任何东西进行排序,那么你应该有以下sortWithConverter函数

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

该程序打印:[7, 5, 2, 1]

最新更新