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

前端 未结 4 1426
时光取名叫无心
时光取名叫无心 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:37

    Something like this could work.

    private List> subListOnFirstLetter(List list) {
        List> result = new ArrayList<>();
        char first = list.get(0).charAt(0);
        List subList = new ArrayList<>();
        for (String element : list) {
            char next = element.charAt(0);
            if (next != first) {
                result.add(subList);
                subList = new ArrayList<>();
            } else {
                subList.add(element);
            }
            first = next;
        }
        return result;
    }
    

提交回复
热议问题