Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

list

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.

like image 522
Hamdan Sultan Avatar asked Dec 19 '22 09:12

Hamdan Sultan


2 Answers

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)));
like image 161
SilverNak Avatar answered Feb 02 '23 01:02

SilverNak


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);
        }
    }
}
like image 35
YCF_L Avatar answered Feb 02 '23 00:02

YCF_L