I have a sorted list in java, i just want to split this list into sublists based on the first alphabet at each index of list. For example List contains
{
cal
If you are open to using a third-party library, Eclipse Collections 7.x will work with Java 6. Using Eclipse Collections MutableList
you can call groupBy
as follows:
MutableList list =
Lists.mutable.with("calculator", "catch", "doll", "elephant");
Multimap multimap =
list.groupBy(StringFunctions.firstLetter());
System.out.println(multimap);
// Prints {d=[doll], e=[elephant], c=[calculator, catch]}
If you need to use a java.util.List
for the Strings, then you can use the ListAdapter
class.
List list =
Arrays.asList("calculator", "catch", "doll", "elephant");
Multimap multimap =
ListAdapter.adapt(list).groupBy(StringFunctions.firstLetter());
Note: I am a committer for Eclipse Collections.