Java 8 – How to build up a string from initial string with only one traversal

  • A+
Category:Languages

I have an url like: String url = "https://.../foo/a/555/data1";

Goal: Transform the url to the string: a555data1

I want to build this result traversing the string only once. I decided for the following process:

  1. I want to "stream" the string starting from the back.
  2. If it is not a backslash insert/append at the front of a deque.
  3. If it is the third backslash end

I have successfully written a horrible solution below, can it be made pretty using streams?

Deque<String> lifo = new ArrayDeque<>();  int count = 0; for (int i = testUrl.length() - 1; count < 3 ; --i) {     if (testUrl.codePointAt(i) == ((int) '/') ) {         ++count;         continue;     }      result.addFirst(testUrl.substring(i,i+1));  }  String foo = result.stream().collect(Collectors.joining()); assertThat(foo).isEqualTo("a606KAM1"); 

 


Another way would be a regex:

String result = url.replaceAll(".+/(.+)/(.+)/(.+)", "$1$2$3"); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: