java - Reducing For loops - Code Optimization -
i new java , looking code optimization techniques. code giving expected output using 2 loops , want reduce/eliminate loops (if possible).
public static void main(string[] args) { string dummy = "hello how you"; string[] strarr = dummy.split(" "); for(int i=0; < strarr.length;i++){ string word = strarr[i]; for(int j=word.length(); j > 0; j--){ system.out.print(word.charat(j - 1)); } system.out.print(" "); } }
output: olleh woh era uoy
please advice.
since complexity of printing output remain same, can "hide" loops existing methods want, not eliminate them, because amount of work system needs perform remains same in terms of number of characters need processed.
you can hide nested loop using string reversal technique described in q&a. outer loop can pushed string.join
:
string[] data = {"quick", "brown", "fox"}; system.out.println( string.join( " " , arrays.stream(data) .map(s -> new stringbuilder(s).reverse().tostring()) .toarray(string[]::new) ) );
Comments
Post a Comment