Create Alphabet List from list : Java

2019-08-29 23:30发布

问题:

I have a list which contains the Filename from a given path,

fileNamesList

and from this list i would like to create a Alphabet list like if there are files name start with A then add A to list and like so upto Z and in the same way i want to create Numbers List also from 0 to 9

All these Alphabet and Number checking is based on Starts with from the file name.

how to do this in java.

Finally the AlphabetList will be like A B E F....Z and the Numbers list will be 1 2 3 9

thanks

回答1:

After initializing AlphabetList:

for (int i = 'A'; i <= 'Z'; i++)
    for (fileName: fileNameList) {
        if ((int)fileName.charAt(0) == i) {
            AlphabetList.add((char)i);
        }
    }
}

You can do a similar thing for NumbersList.

Alternatively:

occurrences = new int[256];
for (fileName: fileNameList) {
    occurrences[(int)fileName.charAt(0)] += 1;
}
for (int i = 'A', i <= 'Z'; i++) {
    if (occurrences[i] > 0) {
        AlphabetList.add((char)i)
    }
}
for (int i = '0', i <= '9'; i++) {
    if (occurrences[i] > 0) {
        NumberList.add(i - '0')
    }
}


回答2:

Similarly you can add logic for number as well

    List alphabetList = new ArrayList();
    int alpha = (int)fileNameList.charAt(0);

    while(alpha <= 90){
        alphabetList.add((char)alpha);
        alpha++;
    }


回答3:

You can use a HashMap<Character, List<String>> to store your lists with a character key. This could serve the same use for numbers and letters but you could create 2 maps if you for some reason want them separated.

private HashMap<Character, List<String>> alphabetList = new HashMap<>();

public void addFileName(String fileName) {
    if(fileName.isEmpty()) {
        return;
    }

    Character firstChar = Character.toUpperCase(fileName.charAt(0));

    List<String> storedList = alphabetList.get(firstChar);
    if(storedList == null) {
        storedList = new ArrayList<String>();
        alphabetList.put(firstChar, storedList);
    }
    storedList.add(fileName);
}