Search code examples
javastringsetstringbuilder

How do I turn a Set<String> into a string in Java?


I have a Set<> of strings:

Set<String> mySet = new HashSet<String>();
    
hs.add("how");
hs.add("are");
hs.add("you");

I want to turn this set into a string, however there is two rules:

  1. ":*" should be added as suffix to each word
  2. The words should be separated with a pipe |

Like this:

"how:*|are:*|you:*"

What is the most simple way to do this?

This is what I've tried so far:

StringBuilder sb = new StringBuilder();

for (String word : search) {
    sb.append(word);
    sb.append(":*|");
}

The problem with this is that it gives an extra pipe in the end:

"how:*|are:*|you:*|"

I can of course delete the last character, but I'm looking for a simpler way if possible.


Solution

  • If you're using Java 8 or later, then String#join is one option. However, you should use an ordered collection to ensure that the strings appear in the order you want:

    List<String> myList = Arrays.asList(new String[] { "how", "are", "you" });
    String output = String.join(":*|", myList) + ":*";
    System.out.println(output);  // how:*|are:*|you:*
    

    You have revealed that you are trying to build a regex alternation to search for a term in your database. If so, then you should be using this pattern:

    .*\b(?:how:|are:|you:).*
    

    The leading and trailing .* might be optional, in the case where the API accepts a pattern matching just a portion of the column. Here is the updated Java code to generate this pattern:

    List<String> myList = Arrays.asList(new String[] { "how", "are", "you" });
    StringBuilder sb = new StringBuilder();
    sb.append(".*\\b(?:").append(String.join(":|", myList)).append(":).*");
    System.out.println(sb.toString);  // .*\b(?:how:|are:|you:).*