Array of size n to array n x 2 using Java 8 stream -


i trying figure out elegant way of converting simple int array (e.g. {1, 2, 3}) simple string array (e.g. {"id", "1", "id", "2", "id", "3"}) of string pairs using java 8 streams.

traditionally code looks this: -

int[] input = {1, 2, 3};  string[] output = new string[input.length * 2];  int = 0; (int val : input) {     output[i++] = "id";     output[i++] = string.valueof(val); } 

but assuming can done in 1-liner in java 8.

string[] result = arrays.stream(input)             .maptoobj(x -> new string[] { "id", "" + x })             .flatmap(arrays::stream)             .toarray(string[]::new); 

or may bit more verbose (but worse since first joining, split after)

string[] result = arrays.stream(input)             .maptoobj(x -> "id" + "," + x)             .collect(collectors.joining(","))             .split(","); 

i can think of these two, it's hardly more readable of have in place simple loop.


Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -