急求java代码 不考虑复姓 用hashmap做,编码格式~
发布网友
发布时间:2022-04-22 05:57
我来回答
共1个回答
热心网友
时间:2023-11-24 17:24
把下面的的名字复制到你的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";
Map<String, Integer> map = createMap(getNames(file));
//sort map
MapComparator comparator = new MapComparator(map);
Map<String, Integer> newMap = new TreeMap<>(comparator);
newMap.putAll(map);
for(Map.Entry<String, Integer> entries : newMap.entrySet()) {
System.out.println(entries.getKey() + " : " + entries.getValue());
}
}
public static Map<String, Integer> createMap(String[] names) {
Map<String, Integer> map = 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<Object> {
Map<String, Integer> map;
public MapComparator(Map<String, Integer> map) {
this.map = map;
}
public int compare(Object o1, Object o2) {
if(map.get(o2) == map.get(o1))
return 1;
else
return ((Integer)map.get(o2)).compareTo((Integer)map.get(o1));
}
}
运行结果:
张 : 3
王 : 2
刘 : 1
李 : 1
追问你好,报了个错