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
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);
}
}
}