1

Got an interesting situation where I'm trying to make use of String.split(regExp, limit) to chunk a big list into smaller lists within a loop. However it seems that when the limit is set beyond 11, it will only ever return a list size off 11. Here's an example below:

Integer CHUNK_SIZE = 15;
Set<String> examples = new Set<String> { 'Cats', 'Dogs', 'Ducks', 'Birds', 'Dogs1', 'Ducks1', 'Birds1', 'Dogs2', 'Ducks2', 'Birds2', 'Dogs3', 'Ducks3', 'Birds3', 'Dogs4', 'Ducks4', 'Birds4', 'Dogs5', 'Ducks5', 'Birds6', 'Dogs6', 'Ducks6', 'Birds7', 'Dogs7', 'Ducks7', 'Birds8'};
List<String> chunkedExamples = examples.toString().substringBetween('{', '}').split(',', CHUNK_SIZE);
System.assertEquals(CHUNK_SIZE, chunkedExamples.size());

Is there an issue with the code snippet or am I misunderstanding how the limit input works? Thanks in advance!

1

1 Answer 1

1

The limit works as you expect, the toString() of Set however, does not. This is what it currently yields;

{Birds, Birds1, Birds2, Birds3, Birds4, Birds6, Birds7, Birds8, Cats, Dogs, ...}

As @RobBaillie commented, this is not a good way to slice the set. There are plenty of code samples of slice methods using the proper data types instead of using string manipulations. Or you could write your own, of course.

3
  • The underlying point being that this isn't a great way of performing the slice. Instead, keep the proper datatypes (Set / List) and process those rather than trying to 'hack' a String representation. Commented Apr 28, 2021 at 10:42
  • I definitely agree. Commented Apr 28, 2021 at 10:43
  • Cheers @rael_kid good to know about how toString() processes the set. Yeah look fair enough about proper data types but sometimes it's fun to experiment! (Just was curious about what was possible). Was genuinely curious as to what was happening.
    – Clint
    Commented Apr 28, 2021 at 12:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .