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
}
i want the sublists as
{calculator,catch}
{doll}
{elephant}
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.
You could use Java 8 Streams. Unfortunately, this method doesn't take advantage from the list being sorted already. list
has to be the list containing your elements.
Map<Character, List<String>> collect =
list.stream().collect(Collectors.groupingBy(elem -> elem.charAt(0)));
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With