Create a list of alphabets from a list: Java

I have a list containing the file name from the given path,

fileNamesList

and from this list I would like to create Alphabet list, as if the file name starts with A, then add A to the list and, like upto Z, and in the same way I want to create Numbers Listalso from0 to 9

All of these alphabet and number checks are based on Starts with from the file name.

how to do it in java.

Finally, AlphabetList will be like A B E F....ZandNumbers list will be 1 2 3 9

thank

0
source share
3 answers

After initialization 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.

As an alternative:

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')
    }
}
+1
source

In the same way, you can also add logic for the number

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

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

You can use HashMap<Character, List<String>>to store lists using a character key. This can be used for numbers and letters, but you can create 2 cards if you want to separate them for some reason.

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);
}
+1
source

All Articles