190. Writing a Function<String, T> for parsing data
Let’s assume that we have the following text:
String text = """
test, a, 1, 4, 5, 0xf5, 0x5, 4.5d, 6, 5.6, 50000, 345,
4.0f, 6$3, 2$1.1, 5.5, 6.7, 8, a11, 3e+1, -11199, 55
""";
The goal is to find a solution that extracts from this text only the numbers. Depending on a given scenario, we may need only the integers, or only the doubles, and so on. Sometimes, we may need to perform some text replacements before extraction (for instance, we may want to replace the xf
characters with a dot, 0xf5 = 0.5
).
A possible solution to this problem is to write a method (let’s name it parseText()
) that takes as an argument a Function<String, T>
. The Function<String, T>
gives us the flexibility to shape any of the following:
List<Integer> integerValues
= parseText(text, Integer::valueOf);
List<Double> doubleValues
= parseText(text, Double::valueOf...