O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The problem – grouping continuous integers

A while back, I wanted a simple and elegant way to solve the following problem:

Given: A sorted list of numbers

When: We group these numbers

Then: Each number in a group is higher by one than its predecessor. So, let's be good and write a few tests first:

 @Test public void testFourGroup() { List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5, 9, 11, 20, 21, 22); List<List<Integer>> groups = groupThem.groupThem(list); assertThat(groups.size(), equalTo(4)); assertThat(groups.get(0), contains(1, 2, 3, 4, 5)); assertThat(groups.get(1), contains(9)); assertThat(groups.get(2), contains(11)); assertThat(groups.get(3), contains(20, 21, 22)); } @Test public void testNoGroup() { List<Integer> emptyList = Lists.newArrayList(); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required