当前位置:网站首页>Numberoptional: a tool for converting strings to numbers
Numberoptional: a tool for converting strings to numbers
2022-07-24 02:39:00 【Lezheng skyline】
NumberOptional: A string to number tool
Doing it Java In development , We often write the following code :
try {
int i = Integer.parseInt(s);
} catch (NumberFormatException e) {
e.printStackTrace();
}
There is only one line of information in this code , But writing is more . It's tedious to write every time , If not try-catch It seems not rigorous 、 unsafe . therefore , Many people choose to package a tool related to digital operation , For example, various numbers Util, The operation code becomes :
int i1 = NumberUtil.parseInt(s);// Parse failure , Default return 0
int i2 = NumberUtil.parse(s, 0);// Provide a default value , Return when parsing fails .
Optional<Integer> intOpt = NumberUtil.parseInt(s);// use Optional To indicate that the parsing failure is empty
//....
Needless to say, the first way above , Unable to control the default value, which makes it not applicable in some scenarios ; The second way , You can control the default value , But when the range of values is all integers , It is impossible to distinguish the failure of parsing . This article shares a tool previously used to process string to number .
Examples of use
Because the function is relatively simple , So go directly to the example code :
String s = "1";
String s2 = "2";
//1. getOr And other overloads are resolved according to the provided default value type , If it doesn't match, return the default value provided
int i1 = NumberOptional.of(s).getOr(1);
float f1 = NumberOptional.of(s).getOr(1f);
//2. orGetXXX Series of methods are used to deal with the fact that the default value is not a fixed value , Or the method of getting the default value is troublesome . Parse the string according to the type of the default value
int i2 = NumberOptional.of(s).orGetInt(() -> Config.getXXXDefault());
//3. xxxOr A series of methods are used to take appropriate values from multiple strings , for example , If s Use when available s Value , otherwise s2 Value , If s2 The value of is still unavailable , Use default values .
int i3 = NumberOptional.of(s).intOr(() -> NumberOptional.of(s2)).getOr(0);
//4. ifXXX The method of is used when the following operations are only executed when the parsing is successful , If you fail, do nothing
NumberOptional.of(s).ifInt(i -> {
System.out.println("is Int:" + i);
});
//5. ifXXXOrElse The method of the series is similar ifXXX, However, you can provide a process to execute when parsing fails .
NumberOptional.of(s).ifIntOrElse(i -> {
System.out.println("is int:" + i);
}, () -> {
System.out.println("is not int");
});
parseOr
public class NumberOptional {
private final String valueString;
private NumberOptional() {
this.valueString = null;
}parseOr
private NumberOptional(String valueString) {
this.valueString = valueString;
}
public static NumberOptional of(String numberStr) {
return new NumberOptional(numberStr);
}
public static NumberOptional of(Object object) {
return new NumberOptional(String.valueOf(object));
}
public NumberOptional longOr(Supplier<? extends NumberOptional> supplier) {
return parseOr(Long::parseLong, supplier);
}
public NumberOptional intOr(Supplier<? extends NumberOptional> supplier) {
return parseOr(Integer::parseInt, supplier);
}
public NumberOptional floatOr(Supplier<? extends NumberOptional> supplier) {
return parseOr(Float::parseFloat, supplier);
}
public NumberOptional doubleOr(Supplier<? extends NumberOptional> supplier) {
return parseOr(Double::parseDouble, supplier);
}
public NumberOptional shortOr(Supplier<? extends NumberOptional> supplier) {
return parseOr(Short::parseShort, supplier);
}
public NumberOptional byteOr(Supplier<? extends NumberOptional> supplier) {
return parseOr(Byte::parseByte, supplier);
}
public long getOr(long defaultValue) {
return parseOrElse(Long::parseLong, defaultValue);
}
public int getOr(int defaultValue) {
return parseOrElse(Integer::parseInt, defaultValue);
}
public short getOr(short defaultValue) {
return parseOrElse(Short::parseShort, defaultValue);
}
public byte getOr(byte defaultValue) {
return parseOrElse(Byte::parseByte, defaultValue);
}
public float getOr(float defaultValue) {
return parseOrElse(Float::parseFloat, defaultValue);
}
public double getOr(double defaultValue) {
return parseOrElse(Double::parseDouble, defaultValue);
}
public long orGetLong(Supplier<Long> supplier) {
return parseOrElseGet(Long::parseLong, supplier);
}
public int orGetInt(Supplier<Integer> supplier) {
return parseOrElseGet(Integer::parseInt, supplier);
}
public short orGetShort(Supplier<Short> supplier) {
return parseOrElseGet(Short::parseShort, supplier);
}
public byte orGetByte(Supplier<Byte> supplier) {
return parseOrElseGet(Byte::parseByte, supplier);
}
public float orGetFloat(Supplier<Float> supplier) {
return parseOrElseGet(Float::parseFloat, supplier);
}
public double orGetDouble(Supplier<Double> supplier) {
return parseOrElseGet(Double::parseDouble, supplier);
}
public void ifLongOrElse(Consumer<Long> parsedConsumer, Runnable elseRunnable) {
ifParseOrElse(Long::parseLong, parsedConsumer, elseRunnable);
}
public void ifIntOrElse(Consumer<Integer> parsedConsumer, Runnable elseRunnable) {
ifParseOrElse(Integer::parseInt, parsedConsumer, elseRunnable);
}
public void ifShortOrElse(Consumer<Short> parsedConsumer, Runnable elseRunnable) {
ifParseOrElse(Short::parseShort, parsedConsumer, elseRunnable);
}
public void ifByteOrElse(Consumer<Byte> parsedConsumer, Runnable elseRunnable) {
ifParseOrElse(Byte::parseByte, parsedConsumer, elseRunnable);
}
public void ifFloatOrElse(Consumer<Float> parsedConsumer, Runnable elseRunnable) {
ifParseOrElse(Float::parseFloat, parsedConsumer, elseRunnable);
}
public void ifDoubleOrElse(Consumer<Double> parsedConsumer, Runnable elseRunnable) {
ifParseOrElse(Double::parseDouble, parsedConsumer, elseRunnable);
}
public void ifLong(Consumer<Long> parsedConsumer) {
ifParse(Long::parseLong, parsedConsumer);
}
public void ifInt(Consumer<Integer> parsedConsumer) {
ifParse(Integer::parseInt, parsedConsumer);
}
public void ifShort(Consumer<Short> parsedConsumer) {
ifParse(Short::parseShort, parsedConsumer);
}
public void ifByte(Consumer<Byte> parsedConsumer) {
ifParse(Byte::parseByte, parsedConsumer);
}
public void ifFloat(Consumer<Float> parsedConsumer) {
ifParse(Float::parseFloat, parsedConsumer);
}
public void ifDouble(Consumer<Double> parsedConsumer) {
ifParse(Double::parseDouble, parsedConsumer);
}
public String get() {
return valueString;
}
private <T> T parseOrElseGet(Function<String, T> parser, Supplier<T> supplier) {
try {
return parser.apply(valueString);
} catch (NumberFormatException | NullPointerException e) {
return supplier.get();
}
}
private <T> T parseOrElse(Function<String, T> parser, T defaultValue) {
try {
return parser.apply(valueString);
} catch (NumberFormatException | NullPointerException e) {
return defaultValue;
}
}
private <T> NumberOptional parseOr(Function<String, T> parser, Supplier<? extends NumberOptional> supplier) {
try {
T i = parser.apply(valueString);
return this;
} catch (NumberFormatException | NullPointerException e) {
return supplier.get();
}
}
private <T> void ifParseOrElse(Function<String, T> parser, Consumer<T> parsedConsumer, Runnable elseRunnable) {
final T i;
try {
i = parser.apply(valueString);
} catch (NumberFormatException | NullPointerException e) {
elseRunnable.run();
return;
}
parsedConsumer.accept(i);
}
private <T> void ifParse(Function<String, T> parser, Consumer<T> parsedConsumer) {
final T i;
try {
i = parser.apply(valueString);
} catch (NumberFormatException | NullPointerException e) {
return;
}
parsedConsumer.accept(i);
}
}
边栏推荐
- 中城院真的在帮助供应商解决问题吗?
- Unity timeline tutorial
- Go basic notes_ 5_ Array slice
- Beansearcher receives array parameters and logical deletion
- IBM: realize the quantum advantage of fault tolerance by 2030
- 【补题日记】[2022牛客暑期多校2]K-Link with Bracket Sequence I
- Pyg uses messagepassing to build GCN to realize node classification
- js传参时传入 string有数据;传入 number时没有数据;2[0]是对的!number类型数据可以取下标
- [datasets] - downloading some datasets of flyingthings3d optical flow
- 【补题日记】[2022杭电暑期多校1]B-Dragon slayer
猜你喜欢

UIE: 信息抽取的大一统模型

Composition API (in setup) watch usage details

wallys/WiFi6 MiniPCIe Module 2T2R2 × 2.4GHz 2x5GHz MT7915 MT7975

This article shows you how to use SQL to process weekly report data

Leetcode 203. remove linked list elements (2022.07.22)

Zone d'entraînement Web d'attaque et de défense (View source, get Post, robots)

Codeworks 5 questions per day (average 1500) - day 23
![[C language] preprocessing details](/img/c3/861165ce20c135f4feedee1f112261.png)
[C language] preprocessing details

因果学习开源项目:从预测到决策!

Recorded on July 21, 2022
随机推荐
JpaRepository扩展接口
关于 SAP Fiori 应用的离线使用
Maximize, minimize, restore, close and move the WinForm form form of C #
JS when transferring parameters, the incoming string has data; No data when number is passed in; 2[0] is right! Number type data can be subscripted
Emmet syntax summary
This article shows you how to use SQL to process weekly report data
Why use the well architected framework?
regular expression
NumberOptional:一个字符串转数字的工具
22 -- 二叉搜索树的范围和
js傳參時傳入 string有數據;傳入 number時沒有數據;2[0]是對的!number類型數據可以取下標
About offline use of SAP Fiori application
508. 出现次数最多的子树元素和-哈希表法纯c实现
TP5 framework link promotion project
【FPGA教程案例38】通信案例8——基于FPGA的串并-并串数据传输
Make life full of happiness
程序员必备技能----断点调试(IDEA版)
【补题日记】[2022牛客暑期多校1]D-Mocha and Railgun
compostion-api(setup中) watch使用细节
[leetcode] sword finger offer 61. shunzi in playing cards