1

Sorry if this is a stupid question, as I am new to Java.

If I have an array like

{ "A123","blue","A456","red","green",
  "B111","purple","C444","blue","green","yellow","pink" }

how can I split this into smaller arrays where the first element should be a letter followed by 3 numbers? For example, the output would be:

{ {"A123","blue"},{"A456","red","green"},
  {"B111","purple"},{"C444","blue","green","yellow","pink"} }

The pattern [A-Z][0-9]{3} could have any number of element after it up until the next occurrence of the pattern.

0

2 Answers 2

2

You can collect a map from this array:

String[] arr = {"A123", "blue", "A456", "red", "green",
        "B111", "purple", "C444", "blue", "green", "yellow", "pink"};

Map<String, List<String>> map = new LinkedHashMap<>();

// assume that first is the 'primary' element
List<String> list = null;
for (String str : arr) {
    // if this is a 'primary' element
    // regex:
    // \\D{1} - first character is non-digit
    // \\d+   - non-empty sequence of digits
    if (str.matches("\\D{1}\\d+")) {
        // put new entry into the map and initialise new list
        list = map.computeIfAbsent(str, el -> new ArrayList<>());
    } else {
        // otherwise, add the 'secondary' element to the list
        list.add(str);
    }
}
// output
map.forEach((k, v) -> System.out.println(k + "=" + v));
//A123=[blue]
//A456=[red, green]
//B111=[purple]
//C444=[blue, green, yellow, pink]

// convert a map to a 2d array, if needed
String[][] arr2d = map.entrySet().stream()
        .map(entry -> Stream
                .concat(Stream.of(entry.getKey()), entry.getValue().stream())
                .toArray(String[]::new))
        .toArray(String[][]::new);
// output
Arrays.stream(arr2d).map(Arrays::toString).forEach(System.out::println);
//[A123, blue]
//[A456, red, green]
//[B111, purple]
//[C444, blue, green, yellow, pink]
Sign up to request clarification or add additional context in comments.

Comments

1

Here is an example:

@Test
public void testArr() {
    String[] strings = new String[]{
            "A123", "blue", "A456", "red", "green",
            "B111", "purple", "C444", "blue", "green", "yellow", "pink"
    };

    List<List<String>> output = new ArrayList<>();
    List<String> currentList = null;
    for (String s : strings) {
        if (s.matches("[A-Z][0-9]{3}")) {
            // start new sub-list
            currentList = new ArrayList<>();
            output.add(currentList);
        }
        currentList.add(s);
    }

    System.out.println(output);
}

It produces:

[[A123, blue], [A456, red, green], [B111, purple], [C444, blue, green, yellow, pink]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.