java - Lambda expression to convert array/List of String to array/List of Integers -


since java 8 comes powerful lambda expressions,

i write function convert list/array of strings array/list of integers, floats, doubles etc..

in normal java, simple

for(string str : strlist){    intlist.add(integer.valueof(str)); } 

but how achieve same lambda, given array of strings converted array of integers.

you create helper methods convert list (array) of type t list (array) of type u using map operation on stream.

//for lists public static <t, u> list<u> convertlist(list<t> from, function<t, u> func) {     return from.stream().map(func).collect(collectors.tolist()); }  //for arrays public static <t, u> u[] convertarray(t[] from,                                        function<t, u> func,                                        intfunction<u[]> generator) {     return arrays.stream(from).map(func).toarray(generator); } 

and use this:

//for lists list<string> stringlist = arrays.aslist("1","2","3"); list<integer> integerlist = convertlist(stringlist, s -> integer.parseint(s));  //for arrays string[] stringarr = {"1","2","3"}; double[] doublearr = convertarray(stringarr, double::parsedouble, double[]::new); 


note s -> integer.parseint(s) replaced integer::parseint (see method references)


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -