Home > Software design >  How do I split a list with fixed size number into another list?
How do I split a list with fixed size number into another list?

Time:06-30

So I have a loop in regex,

List<String> data = new ArrayList<>();
List<String> inputData = // String array

Pattern pattern = Pattern.compile(regex);
inputData.forEach(i -> {
    Matcher matcher = pattern.matcher(i);
    while(matcher.find()) {
        data.add(matcher.group().trim());
    }
});

Now data will have an array of strings like this,

data = ['text', 'text2', 'text3', 'text4', 'text5', 'text6']

I want to divide this array of strings into a fixed size of 3.

data = [['text', 'text2', 'text3'], ['text4', 'text5', 'text6']]

CodePudding user response:

If you want to split this list into sublist with fixed size - you can use Guava, or smth else

You can find related docs here - https://guava.dev/releases/31.0-jre/api/docs/com/google/common/collect/Lists.html#partition(java.util.List,int)

Example:

    List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
    List<List<Integer>> subSets = Lists.partition(intList, 3);
  • Related