有沒有辦法過濾掉所有大于可以存盤在Long使用 Stream API 中的最大值的值?
目前的情況是,您可以使用他們的ID在一些客戶之后通過簡單的搜索欄在前端進行搜索。
例如:123456789, 10987654321.如果您在這兩個 ID 之間放置一個“分隔符” ,則一切正常。但是,如果您忘記了“分隔符”,我的代碼正試圖決議12345678910987654321為 Long,我想這就是問題所在。
這會導致NumberFormatException嘗試搜索之后。Long有沒有辦法過濾掉這些因為太大而無法決議為 a 的數字?
String hyphen = "-";
String[] customerIds = bulkCustomerIdProperty.getValue()
.replaceAll("[^0-9]", hyphen)
.split(hyphen);
...
customerFilter.setCustomerIds(Arrays.asList(customerIds).stream()
.filter(n -> !n.isEmpty())
.map(n -> Long.valueOf(n)) // convert to Long
.collect(Collectors.toSet()));
uj5u.com熱心網友回復:
您可以將決議提取到一個單獨的方法中并用 包裝它try/catch,或者使用它BigInteger來消除超出范圍的值long。
示例BigInteger:
Set<Long> result = Stream.of("", "12345", "9999999999999999999999999999")
.filter(n -> !n.isEmpty())
.map(BigInteger::new)
.filter(n -> n.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) <= 0 &&
n.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) >= 0)
.map(BigInteger::longValueExact) // convert to Long
.peek(System.out::println) // printing the output
.collect(Collectors.toSet());
NumberFormatException以單獨方法處理的示例:
Set<Long> result = Stream.of("", "12345", "9999999999999999999999999999")
.filter(n -> !n.isEmpty())
.map(n -> safeParse(n))
.filter(OptionalLong::isPresent)
.map(OptionalLong::getAsLong) // extracting long primitive and boxing it into Long
.peek(System.out::println) // printing the output
.collect(Collectors.toSet());
public static OptionalLong safeParse(String candidate) {
try {
return OptionalLong.of(Long.parseLong(candidate));
} catch (NumberFormatException e) {
return OptionalLong.empty();
}
}
輸出(來自peek())
12345
uj5u.com熱心網友回復:
也許您可以添加另一個過濾器,例如
.filter((n) -> { return new BigInteger(n).compareTo(new BigInteger(String.valueOf(Long.MAX_VALUE))) <= 0;})
發生這種情況時,您還可以使用 try/catch 拋出錯誤并通知您的前端
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/458712.html
