Ed Staub
Ed Staub

Reputation: 15690

How does one efficiently partition an already-sorted list into groups, possibly using Guava?

I have an array that logically contains multiple groups of elements, where each group is contiguous in the array. (It was sorted via a database "order by" clause). It would be cleanest to traverse this as a collection of collections (in a loose sense - an iterator of iterators is fine) where the top-level iterator would return one lower-level iterator for each group. This might work similarly to Guava's partition(), but using a passed-in comparator to figure out where to break up the input.

There are lots of inefficient ways to do this, such as using Guava's MultiMap. Is there a simple, off-the-shelf, efficient way to do it that takes advantage of the ordering?

Upvotes: 4

Views: 288

Answers (1)

John Smith
John Smith

Reputation: 2330

Write your own iterators.

The first one returns instances of the second one.

They share an index!

The second one returns true for hasNext() as long as the index is on elements of the same group. when second's.hasNext() returns false call first.hasNext() and then first.next() and so on.

It should be 5 - 10 lines of hand written code (assuming your IDE does all the class, method and brackets stuff).

That's an efficient and not too ugly way of doing things. If you want to be more efficient simply walk through the array, checking the group condition within a for loop. That's even less code propably.

Upvotes: 1

Related Questions