Let's say a directory is inputted by user.
How do I sort and count all files based on their name's first letter? I suppose there has to be a comparator for sorting but I got no idea what to do with counting.
Asked
Active
Viewed 1,066 times
-3
-
first letter? Alphabet? – SMA Dec 31 '14 at 12:28
-
an `HashMap` (letter as key, count as value) might do the job – Dec 31 '14 at 12:31
5 Answers
1
a classic way to do that is make a Map with each letter a key and the count for that letter the value
List<String> names = new ArrayList<>();
Map<Character,Integer> map = new HashMap<>();
for (String name : names)
{
char firstLetter = name.charAt(0);
if( map.containsKey(firstLetter) )
map.put(firstLetter, map.get(firstLetter)+1 );
else
map.put(firstLetter, 1);
}

Peter
- 5,728
- 20
- 23
1
If you are using java-8 there is an elegant way to do this:
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
...
Map<Character, Long> countMap = Files.list(Paths.get("some/directory"))
.filter(p -> !Files.isDirectory(p))
.collect(groupingBy(p -> p.getFileName().toString().charAt(0), counting()));
What it does is:
- get a
Stream<Path>
from the directory given - get only files by applying a filtering
- collect each file in a
Map<Character, List<Path>>
, grouping by their first letter - count the number of elements in each
List<Path>

Alexis C.
- 91,686
- 21
- 171
- 177
0
Using the Google Guava TreeMultiset makes it easy:
public static void main(String[] args) throws Exception {
File dir = new File(*<directory>*);
Multiset<Character> counts = TreeMultiset.create();
for(File file: dir.listFiles()) {
counts.add(file.getName().charAt(0));
}
System.out.println(counts);
}

BarrySW19
- 3,759
- 12
- 26
0
Try something like:
File mydirectory = new File("c:\\users");
Map<Character, Integer> alpaCount = new HashMap<Character, Integer>();
Character firstChar;
Integer count;
for (File file : mydirectory.listFiles()) {
firstChar = file.getName().charAt(0);
count = alpaCount.get(firstChar);
if (count == null) {
alpaCount.put(firstChar, 1);
} else {
alpaCount.put(firstChar, count + 1);
}
}

SMA
- 36,381
- 8
- 49
- 73