-3

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.

Matt
  • 45,022
  • 8
  • 78
  • 119
danchy
  • 447
  • 2
  • 7
  • 18

5 Answers5

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 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

Take a look at this post, they are using listFiles function. Then you would be able to count and do whatever you want with file names. I don't think there is an existing function for retrieving exactly what you need ...

Community
  • 1
  • 1
Ko2r
  • 1,541
  • 1
  • 11
  • 24
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