Malik Brahimi
Malik Brahimi

Reputation: 16711

Splitting a list into groups

I have a list of strings and I was wondering if there was an easy way to join the elements in groups of size n, where the last elements would be automatically handled if less than n. For example,

String[] strings = {"A", "man", "a", "plan", "a", "canal", "Panama"};

The expected output for n = 3 would be the following list of strings. Remember, I can use some exhausting iteration to do this myself, but I'm looking for something simple. Perhaps something built-in to the standard library.

String[] output = {"A man a", "plan a canal", "Panama"};

As comparison, I would like to demonstrate the simplicity of the task in Python. I am looking for an equally as simple solution in Java.

[' '.join(strings[i:i+3]) for i in range(0, len(strings), 3)]

Upvotes: 2

Views: 2720

Answers (2)

Oziris
Oziris

Reputation: 176

I don't know a lib for this, but the method is pretty easy to write :

    public static String[] group(int groupsize, String separator, String[] strings) {

    List<String> output = new ArrayList<>();
    StringBuilder sb = new StringBuilder();

    int index = 0;

    for (String string : strings) {

        if (index > 0) {
            sb.append(separator);
        }

        sb.append(string);

        index++;

        if (index >= groupsize) {
            index = 0;
            output.add(sb.toString());
            sb = new StringBuilder();
        }
    }

    if(index > 0) {
        output.add(sb.toString());
    }

    return output.toArray(new String[output.size()]);
}

You can also use Guava for partitionning and join, but for this kind of simple process, the method above seems pretty easy to understand.

Also Guava will need to iterate 2 times on your string array : One for partitionning, and one for concatenate. So it should be less efficient to use Guava

Upvotes: 0

Adam
Adam

Reputation: 36723

  • Guava - a Java utility library by Google, has a partition method Lists.partition(list, size) which you can use to split the list into groups of 3
  • Java 8 has String.join(separator, iterable), or Guava's Joiner.join()
  • Collections like Lists generally better to work with than primitive arrays...

Example, assuming you didn't have access to Guava.

public static void main(String[] args) {
    String[] strings = { "A", "man", "a", "plan", "a", "canal", "Panama" };

    List<String> output = new ArrayList<String>();
    for (List<String> partition : partition(Arrays.asList(strings), 3)) {
        output.add(String.join(" ", partition));
    }
    System.out.println(Arrays.toString(output.toArray()));
}

private static <T> List<List<T>> partition(List<T> input, int size) {
    List<List<T>> lists = new ArrayList<List<T>>();
    for (int i = 0; i < input.size(); i += size) {
        lists.add(input.subList(i, Math.min(input.size(), i + size)));
    }
    return lists;
}

Upvotes: 3

Related Questions