forked from Apress/functional-interfaces-in-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberParser.java
More file actions
31 lines (29 loc) · 979 Bytes
/
NumberParser.java
File metadata and controls
31 lines (29 loc) · 979 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package chapter4;
import java.util.function.Function;
import java.util.ArrayList;
public class NumberParser
{
private static <Y extends Number> Y parse(String x,
Function<String, Y> f)
{
return f.apply(x);
}
public static void main(String[] args)
{
ArrayList< Function<String,? extends Number> > list
= new ArrayList<>();
list.add(x -> Byte.parseByte(x));
list.add(x -> Short.parseShort(x));
list.add(x -> Integer.parseInt(x));
list.add(x -> Long.parseLong(x));
list.add(x -> Float.parseFloat(x));
list.add(x -> Double.parseDouble(x));
String[] numbers = {"10", "20", "30", "40", "50", "60"};
Number[] results = new Number[numbers.length];
for (int i=0; i < numbers.length; ++i)
{
results[i] = parse(numbers[i], list.get(i));
System.out.println(results[i]);
}
}
}