Java 根据文件名的第一个字母对文件进行排序和计数

Java 根据文件名的第一个字母对文件进行排序和计数,java,file,sorting,counting,java-8,Java,File,Sorting,Counting,Java 8,假设一个目录是由用户输入的。 如何根据文件名的第一个字母对所有文件进行排序和计数?我想必须有一个用于排序的比较器,但我不知道如何进行计数。看看post,它们使用的是listFiles函数。然后,您将能够计算并使用文件名执行任何您想要的操作。我不认为有一个现有的函数可以准确地检索您需要的内容 一种经典的方法是制作一个地图,每个字母都是一个键,该字母的计数是一个值 List<String> names = new ArrayList<>(); Map<Character

假设一个目录是由用户输入的。

如何根据文件名的第一个字母对所有文件进行排序和计数?我想必须有一个用于排序的比较器,但我不知道如何进行计数。

看看post,它们使用的是listFiles函数。然后,您将能够计算并使用文件名执行任何您想要的操作。我不认为有一个现有的函数可以准确地检索您需要的内容

一种经典的方法是制作一个地图,每个字母都是一个键,该字母的计数是一个值

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);
  }
List name=new ArrayList();
Map Map=newhashmap();
for(字符串名称:名称)
{
char firstLetter=name.charAt(0);
if(地图容器(第一个字母))
map.put(第一个字母,map.get(第一个字母)+1);
其他的
地图放置(第一个字母,1);
}

使用Google Guava TreeMultiset可以轻松:

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);
}
publicstaticvoidmain(字符串[]args)引发异常{
文件目录=新文件(**);
Multiset counts=TreeMultiset.create();
对于(文件:dir.listFiles()){
counts.add(file.getName().charAt(0));
}
系统输出打印项次(计数);
}
尝试以下方法:

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);
   }
}
File mydirectory=新文件(“c:\\users”);
Map alpaCount=新HashMap();
字符firstChar;
整数计数;
对于(文件:mydirectory.listFiles()){
firstChar=file.getName().charAt(0);
count=alpaCount.get(firstChar);
如果(计数=null){
阿尔帕伯爵.普特(firstChar,1);
}否则{
alpaCount.put(firstChar,count+1);
}
}
如果您正在使用,有一种优雅的方法可以做到这一点:

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()));
导入静态java.util.stream.Collectors.counting;
导入静态java.util.stream.Collectors.groupingBy;
...
Map countMap=Files.list(path.get(“some/directory”))
.filter(p->!Files.isDirectory(p))
.collect(分组方式(p->p.getFileName().toString().charAt(0),counting());
它所做的是:

  • 从给定目录中获取
  • 通过应用筛选仅获取文件
  • 收集
    地图中的每个文件,按其第一个字母分组
  • 计算每个
    列表中的元素数

第一个字母?字母表?一个
HashMap
(字母作为键,计数作为值)可以完成这项工作