Split alphabetically sorted list in alphabetical based sublists in java

I have a sorted list in java, I just want to split this list into sub-lists based on the first alphabet in each index of the list. For example, the list contains

{
calculator,
catch,
doll,
elephant
}

I want sublists to be

{calculator,catch}
{doll}
{elephant}

I do not want to give statements if 26 if there is an effective and correct way to do this. The list is already sorted alphabetically. Any help would be greatly appreciated.

+4
source share
4 answers

@SilverNak's solution works well with Java-8, you can use this as well 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);
        }
    }
}
+3
source

Java 8. , . list , .

Map<Character, List<String>> collect =
        list.stream().collect(Collectors.groupingBy(elem -> elem.charAt(0)));
+6

If you are open to using a third-party library, Eclipse Collections 7.x will work with Java 6. MutableListYou can call the use of Eclipse collections groupByas follows:

MutableList<String> list = 
        Lists.mutable.with("calculator", "catch", "doll", "elephant");
Multimap<Character, String> multimap = 
        list.groupBy(StringFunctions.firstLetter());
System.out.println(multimap); 
// Prints {d=[doll], e=[elephant], c=[calculator, catch]}

If you need to use java.util.Listfor strings, you can use a class ListAdapter.

List<String> list =
        Arrays.asList("calculator", "catch", "doll", "elephant");
Multimap<Character, String> multimap =
        ListAdapter.adapt(list).groupBy(StringFunctions.firstLetter());

Note. I am a committer for Eclipse collections.

+1
source

Something like this might work.

private List<List<String>> subListOnFirstLetter(List<String> list) {
    List<List<String>> result = new ArrayList<>();
    char first = list.get(0).charAt(0);
    List<String> subList = new ArrayList<>();
    for (String element : list) {
        char next = element.charAt(0);
        if (next != first) {
            result.add(subList);
            subList = new ArrayList<>();
        } else {
            subList.add(element);
        }
        first = next;
    }
    return result;
}
0
source

Source: https://habr.com/ru/post/1671871/


All Articles