Split and loop in java 8

I have this problem that I want to solve in java 8,

I have a string that concatenates .

 ABCD 

The number of characters per line may vary.

I have this method that takes a string as input and the number of levels that it should go through. I have to go through the number that I get after applying line breaks with "." and go only to a given level of depth

 private String getResponse (String str, int level) { // for now, simply print the entire string first and then start removing last alphabet of it one by one till the value of level // ex : str = ABCD // System.out.println("Doing a call with key as = " + str); => should give me ABCD // Apply logic of split // System.out.println("Doing a call with key as = " + str); => should give me ABC // Split again // System.out.println("Doing a call with key as = " + str); => should give me AB // this should go in loop till we reach the level } 

Can this be done in java 8?

+5
source share
5 answers

Here's the 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 you know for sure that the level does not exceed the number of points, you can omit the check:

 static void getResponseUnsafe(String input, int level) { Stream.iterate(input, str -> str.substring(0, str.lastIndexOf('.'))) .limit(level + 1).forEach(System.out::println); } 
+10
source

No loop is required since a string can be split into an array in one call to String.split . (Note that String.split accepts a regular expression.) To handle the "level", simply subtract it from the length of the section array. Instead of copying the array subrange, convert it to a list and use subList ():

 String getResponse(String str, int level) { String[] splits = str.split("\\."); if (level < 0 || level > splits.length) { throw new IllegalArgumentException(); } return String.join(".", Arrays.asList(splits).subList(0, splits.length - level)); } 

Conclusion

  for (int level = 0; level < 5; level++) { System.out.printf("level %d: %s%n", level, getResponse("ABCD", level)); } 

will be

 level 0: ABCD level 1: ABC level 2: AB level 3: A level 4: 

Please note that this requires Java 8, because it requires String.join() . (But it does not require threads or even lambda!)

+5
source

Note. Using Java 8

 public class StringLoop { public static void main(String[] args) { getResponse("ABCD", 2); System.out.println(); getResponse("ABCD", 3); } // Recursive function private static void getResponse (String str, int level) { if(level < 0 || str.equals("")) return; // Prints out the current string System.out.println(str); int lastIndex = str.lastIndexOf("."); if(lastIndex == - 1) lastIndex = 0; // Remove content after last connector // Decrement level getResponse(str.substring(0, lastIndex), level - 1); } } 

Conclusion:

 ABCD ABC AB ABCD ABC AB A 
+2
source

Your comments mention the use of split() , so here is an example of using split() , Arrays.copyOfRange() (to remove the last letter) and String.Join() to return the result of Arrays.copyOfRange() back for the next recursive call.

 public static void main(String[] args) { String string = "ABCD"; getResponse(string, 3); System.out.println(); getResponse(string, 2); System.out.println(); getResponse(string, 1); System.out.println(); } private static void getResponse(String str, int level) { if (level < 0 || str.isEmpty()) return; System.out.println(str); String[] strPieces = str.split("\\."); if (strPieces.length > level) { getResponse(String.join(".", Arrays.copyOfRange(strPieces, 0, strPieces.length - 1)), level - 1); } } 

Results:

 ABCD ABC AB A ABCD ABC AB ABCD ABC 
+2
source

If you are only interested in the result of String , there is no need to create an intermediate String and split it into several parts to bring them together. Just iterate over the appropriate index into String and create one String result:

 static String getResponse(String str, int level) { for(int index=str.length(); index>0; index=str.lastIndexOf('.', index-1)) if(level-- == 0) return str.substring(0, index); if(level==0) return ""; throw new IllegalArgumentException(str+" has not enough dots"); } 

It does not use any Java 8 function, but it is also hard to imagine how Java 8 functions can improve this simple operation ...

+1
source

All Articles