How to keep Storing data to a String until a symbol shows in the Array List?

Viewed 46

I am trying to store data from ArrayList to Strings until a symbol shows up. So for example, there is an ArrayList with the following Items:

{Start, at , - , Bob, amazing, gold, -, Peter, pan, Bright, shine, - , Sugar, shack -, lol, -}

I put random names for demonstration, but anywho I am trying to store data in a String until it sees a symbol. So For the above list, data will be stored in multiple strings in the following way:

String first = "Start at"
String second = "Bob amazing gold"
String third  = "Peter pan bright shine"
String forth = "Sugar shack"
String fifth = "lol"

The above list is just an example. I am trying to implement a code that works with any list. So there is no pattern. The code should keep strong data to a String until it sees a symbol. Any ideas on how I can accomplish this? Please let me know!

2 Answers

You can iterate through each element of your list and chain the strings which doesn't contain symbols. Then you could store your result in a List.

public static void main(String[] args) {

    List<String> wordList = Arrays.asList("Start", "at", "-", "Bob", "amazing", "gold", "-", "Peter", "pan", "Bright", "shine", "-", "Sugar", "shack", " -", "lol", "-");
    List<String> result = new ArrayList<>();
    StringBuilder builder = new StringBuilder();
    for (String word : wordList) {
        if (isSymbol(word)) {
            result.add(builder.toString());
            builder = new StringBuilder();
        } else {
            if (builder.length() != 0) {
                builder.append(' ');
            }
            builder.append(word);
        }
    }
    if (builder.length() > 0) {
        result.add(builder.toString());
    }
    System.out.println(result);
}

public static boolean isSymbol(String name) {
    return name.matches("[ -]+");
}

May be simpler:

public static void main(String[] args) {
    List<String> wordList = Arrays.asList("Start", "at", "-", "Bob", "amazing", "gold", "-", "Peter", "pan", "Bright", "shine", "-", "Sugar", "shack", " -", "lol", "-");
    List<String> result = new ArrayList<>();
    StringBuilder builder = new StringBuilder();

    for (String word : wordList) {
        builder.append(word).append(" ");
    }

    String[] splits = builder.toString().split(" -");
    result.addAll(Arrays.asList(splits));

    System.out.println(result);
}
Related