把下面的的名字复制到你的names.txt中,保存在和你的java同一目录下
王二,李大,张三,张四,王五,刘一,张长
Java代码如下
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class ReadSurname {
public static void main(String[] args) throws Exception {
String file = "你存放txt格式的地址/names.txt";
Mapmap = createMap(getNames(file));
//sort map
MapComparator comparator = new MapComparator(map);
MapnewMap = new TreeMap<>(comparator);
newMap.putAll(map);
for(Map.Entryentries : newMap.entrySet()) {
System.out.println(entries.getKey() + " : " + entries.getValue());
}
}
public static MapcreateMap(String[] names) {
Mapmap = new HashMap<>();
for(String name : names) {
String surname = name.substring(0,1);
if(map.containsKey(surname)) {
Integer counter = map.get(surname);
counter ++;
map.replace(surname, counter);
} else {
map.put(surname, 1);
}
}
return map;
}
public static String[] getNames(String file) throws Exception{
File fileLocation = new File(file);
byte[] buf = Files.readAllBytes(fileLocation.toPath());
String names = new String(buf, StandardCharsets.UTF_8);
return names.split("\\,");
}
}
class MapComparator implements Comparator
运行结果:
张 : 3
王 : 2
刘 : 1
李 : 1