Java-8 – pass the Java 8 stream mapping function as a parameter
I have a comma separated string that I want to convert to an array But in some cases, I need integer parsing, and sometimes I need to double
return Arrays.stream(test.split(",")).mapToDouble(x -> { if (StringUtils.isEmpty(x)) { return condition ? -1 : 0; } return Double.parseDouble(x); }).toArray(); return Arrays.stream(test.split(",")).mapToInt(x -> { if (StringUtils.isEmpty(x)) { return condition ? -1 : 0; } return Integer.parseInt(x); }).toArray();
Is there any way to turn it into a function that I can have a generic function and store the appropriate array?
Solution
You can do this with a simple function that accepts string and function < string, t > This function is used to convert each string element The good news is that this function can return any type you want: integer, double, BigDecimal, string or any other type you want In the following example, I use method references, such as:
>Integer:: valueof convert element to integer value > double:: valueof convert element to double value > string:: valueof convert element to string value
Consider the following examples:
import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; public class ParsingStringTest { public static void main(String[] args) { String str = "1,3,4,5,7,sasd,aaa,0"; List<Double> doubles = parse(str,Double::valueOf); List<Integer> integers = parse(str,Integer::valueOf); List<String> strings = parse(str,String::valueOf); System.out.println(doubles); System.out.println(integers); System.out.println(strings); Double[] array = doubles.toArray(new Double[doubles.size()]); System.out.println(Arrays.toString(array)); } public static <T> List<T> parse(String str,Function<String,T> parseFunction) { return Arrays.stream(str.split(",")) .filter(s -> !s.isEmpty()) .map(s -> { try { return parseFunction.apply(s.trim()); } catch (Exception e) {} return null; }) .filter(Objects::nonNull) .collect(Collectors.toList()); } }
The console output for the following example is:
[1.0,3.0,4.0,5.0,7.0,0.0] [1,0] [1,0] [1.0,0.0]
I hope it helps