根据Java中的字母将按字母顺序排序的列表拆分为子列表 [英] Split a alphabetically sorted list into sublists based on alphabets in 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);
}
}
}
这篇关于根据Java中的字母将按字母顺序排序的列表拆分为子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文