简体   繁体   中英

Java 8 streams to split and collect tokens

I have an input like this

abc|label1 cde|label2 xyz|label1 mno|label3 pqr|label2

And I want to create a string like this

"abc cde xyz mno pqr"

This is how far I got

 Arrays.stream(text.split(" "))
       .map(i -> i.split("\\|"))
       .collect(Collectors.joining(" "));

You are close, but you forgot to take just the first element of the String array returned by the inner split :

Arrays.stream(text.split(" "))
      .map(i -> i.split("\\|")[0])
      .collect(Collectors.joining(" "));

This produces the desired String :

abc cde xyz mno pqr

If you want to take a different approach, I suggest using regular expressions. I use regex101.com on a daily basis to build various expressions for my applications. Here's how I would use regex in your situation:

String input = "abc|label1 cde|label2 xyz|label1 mno|label3 pqr|label2";
Pattern p = Pattern.compile("\\w+(?=\\|)");
Matcher m = p.matcher(input);

StringJoiner joiner = new StringJoiner(" ");
while(m.find()) {
    joiner.add(m.group());
}

System.out.println(joiner.toString());

You can also use Andreas ' expression, which takes care of it in much fewer lines (I changed it a bit to compensate for the potential absence of white-space):

String input = "abc|label1 cde|label2 xyz|label1 mno|label3 pqr|label2";
input = String.join(" ", input.split("\\|\\w+\\d\\s*"));
System.out.println(input);

Both solutions produce the desired result:

abc cde xyz mno pqr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM