Helquin Helquin - 4 months ago 23
Java Question

Sorting names and storing them to an Array cell with LinkedList

So the idea is to get an input which is a

(a name to be specific), then store it in an
with the size of 26 to its respective cell. The sorting goes this way: names that start with 'A' goes to cell 0, names that start with 'B' goes to cell 1 and so on. Now, a cell contains a
where the names are sorted again alphabetically.

So far, the approach I made is by using the switch case.

private void addDataAList(AuthorList[] aL, String iN) {
char nD = Character.toUpperCase(iN.charAt(0));
case 'A':
AuthorList[0] = iN;

case 'B':
AuthorList[1] = iN;
//and so on

is there a more efficient way to do this?


Assuming that AuthorList class may look like this:

private class AuthorList{
    private LinkedList<String> nameList;

    public AuthorList() {

    public AuthorList(LinkedList<String> nameList) {
        this.nameList = nameList;

    public LinkedList<String> getNameList() {
        return nameList;

    public void setNameList(LinkedList<String> nameList) {
        this.nameList = nameList;

    public String toString() {
        final StringBuilder sb = new StringBuilder("AuthorList{");
        return sb.toString();

I'd make it like this:

private static void addDataAList(AuthorList[] aL, String iN) {
    int index = Character.toUpperCase(iN.trim().charAt(0)) - 'A';
    try {
        AuthorList tmpAuthorList = aL[index];
        if(tmpAuthorList == null) aL[index] = tmpAuthorList = new AuthorList(new LinkedList<>());
        if(tmpAuthorList.getNameList() == null) tmpAuthorList.setNameList(new LinkedList<>());
    } catch (ArrayIndexOutOfBoundsException aioobe){
        throw new IllegalArgumentException("Name should start with character A - Z");

And additional main method for test purposes:

public static void main (String[] args){
    AuthorList[] aL = new AuthorList[26];
    addDataAList(aL, " dudeman");
    for (AuthorList list : aL) System.out.println(list);