i have problem want solve in java 8,
i have string concatenated .
a.b.c.d
number of characters in string can vary.
i have method, takes string input , number of level deep has go, have loop through number after applying split on string "." , go given level deep
private string getresponse (string str, int level) { // now, print entire string first , start removing last alphabet of 1 one till value of level // ex : str = a.b.c.d // system.out.println("doing call key = " + str); => should give me a.b.c.d // apply logic of split // system.out.println("doing call key = " + str); => should give me a.b.c // split again // system.out.println("doing call key = " + str); => should give me a.b // should go in loop till reach level }
can done in java 8?
here's java-8 solution:
static void getresponse(string input, int level) { stream.iterate(input, str -> { int pos = str.lastindexof('.'); return pos == -1 ? "" : str.substring(0, pos); }).limit(level+1).foreach(system.out::println); }
if know sure level not exceed number of dots, can omit check:
static void getresponseunsafe(string input, int level) { stream.iterate(input, str -> str.substring(0, str.lastindexof('.'))) .limit(level + 1).foreach(system.out::println); }
Comments
Post a Comment