Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Collections: How to divide a sorted list into sub lists

Let's say I have a list (EG: LinkedList<SomeObject>that contains elements ordered by a certain attribute (EG: SomeObject.someValue()). This attribute can and usually does repeat often/it isn't unique, BUT is never null.

Is there a convenient way to divide this into multiple Lists, each list containing only its equal in cardinal order? Also, can this be done with only once iteration of the list? For example, the original list:

1, 1, 1, 2, 2, 3, 3, 3

The desired lists from this:

1, 1, 1
2, 2,
3, 3, 3
like image 489
Zombies Avatar asked Nov 29 '22 11:11

Zombies


1 Answers

Not too convenient, but:

  • start a loop. Store the previous item, and compare it to the current.
  • if the previous is different from the current (using equals(..), and be careful with null), then create a new List, or use list.subList(groupStart, currentIdx)
like image 156
Bozho Avatar answered Dec 05 '22 15:12

Bozho