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

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

    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> map = new HashMap<>();
    
        List 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);
            }
        }
    }
    

提交回复
热议问题