我需要對字串串列進行排序,將它們作為 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());
我可以在不明確指定型別的情況下以某種方式執行此操作嗎?
uj5u.com熱心網友回復:
你可以這樣做。
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]
您也可以這樣做,但需要將型別引數宣告為字串。
List<String> sortedStrings = strings
.stream()
.sorted(Comparator.comparing((String p)->new BigDecimal(p)).reversed())
.collect(Collectors.toList());
但這是我推薦的方法。BigDecimal 實作了該Comparable介面。因此,您只需將所有值映射到BigDecimal,按相反順序對它們進行排序,然后再轉換回字串。否則,其他解決方案將繼續實體化一個BigDecimal物件只是為了排序,這可能會導致許多實體化。
List<String> sortedStrings = strings
.stream()
.map(BigDecimal::new)
.sorted(Comparator.reverseOrder())
.map(BigDecimal::toString)
.collect(Collectors.toList());
System.out.println(sortedStrings);
uj5u.com熱心網友回復:
如果您想要一個可以通過將其轉換為另一個類來對任何內容進行排序的函式,您應該擁有以下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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/386782.html
標籤:爪哇
