Split a alphabetically sorted list into sublists based on alphabets in java

前端 未结 4 1420
时光取名叫无心
时光取名叫无心 2021-01-19 06:20

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         


        
4条回答
  •  有刺的猬
    2021-01-19 06:23

    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.

提交回复
热议问题