根据Java中的字母将按字母顺序排序的列表拆分为子列表

根据Java中的字母将按字母顺序排序的列表拆分为子列表

问题描述:

我在Java中有一个排序列表,我只想根据列表的每个索引的第一个字母将此列表拆分为子列表.例如 列表包含

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

{
calculator,
catch,
doll,
elephant
}

我希望子列表为

{calculator,catch}
{doll}
{elephant}

我不想放置26个if语句,是否有任何有效且正确的方法来执行此操作.该列表已按字母顺序排序. 任何帮助将不胜感激.

I dont want to put 26 if statements, is there any efficient and correct way of doing this. The list is already sorted alphabetically. Any help will be highly appreciated.

@SilverNak的解决方案在Java-8上很好,如果您不使用Java-8,也可以使用它:

The solution of @SilverNak is good with Java-8, you can use this also if you are not using Java-8 :

public static void main(String[] args) {
    String list[] = {"calculator", "catch", "doll", "elephant"};
    Map<Character, List<String>> map = new HashMap<>();

    List<String> lst;
    for (String str : list) {
        //if the key exit then add str to your list else add a new element
        if (map.containsKey(str.charAt(0))) {
            map.get(str.charAt(0)).add(str);
        } else {
            lst = new ArrayList<>();
            lst.add(str);
            map.put(str.charAt(0), lst);
        }
    }
}