gpt4 book ai didi

java - 如何从 .t​​xt 文件中读取字符串并根据出现次数将它们排序到 ArrayList 中?

转载 作者:行者123 更新时间:2023-12-01 12:53:36 25 4
gpt4 key购买 nike

我有一个程序,它读取 .txt 文件,创建一个包含每个唯一字符串及其出现次数的 HashMap,并且我想创建一个 ArrayList,根据其出现次数按降序显示这些唯一字符串。

目前,我的程序从字母顺序的角度按降序排序(我假设使用 ASCII 值)。

如何按出现次数降序排列?

这是代码的相关部分:

            Scanner in = new Scanner(new File("C:/Users/ahz9187/Desktop/counter.txt"));
while(in.hasNext()){
String string = in.next();


//makes sure unique strings are not repeated - adds a new unit if new, updates the count if repeated
if(map.containsKey(string)){
Integer count = (Integer)map.get(string);
map.put(string, new Integer(count.intValue()+1));
} else{
map.put(string, new Integer(1));
}
}
System.out.println(map);

//places units of map into an arrayList which is then sorted
//Using ArrayList because length does not need to be designated - can take in the units of HashMap 'map' regardless of length

ArrayList arraylist = new ArrayList(map.keySet());
Collections.sort(arraylist); //this method sorts in ascending order

//Outputs the list in reverse alphabetical (or descending) order, case sensitive

for(int i = arraylist.size()-1; i >= 0; i--){
String key = (String)arraylist.get(i);

Integer count = (Integer)map.get(key);
System.out.println(key + " --> " + count);
}

最佳答案

在 Java 8 中:

public static void main(final String[] args) throws IOException {
final Path path = Paths.get("C:", "Users", "ahz9187", "Desktop", "counter.txt");
try (final Stream<String> lines = Files.lines(path)) {
final Map<String, Integer> count = lines.
collect(HashMap::new, (m, v) -> m.merge(v, 1, Integer::sum), Map::putAll);
final List<String> ordered = count.entrySet().stream().
sorted((l, r) -> Integer.compare(l.getValue(), r.getValue())).
map(Entry::getKey).
collect(Collectors.toList());
ordered.forEach(System.out::println);
}
}

首先使用 Files.lines 读取文件方法给你一个 Stream<String>行。

现在将这些行收集到 Map<String, Integer> 中使用Map.merge方法,它接受一个键和一个值,以及一个应用于旧值和新值(如果键已经存在)的 lambda。

您现在已经掌握了计数。

现在取 Stream entrySetMap的并按 value 排序每个Entry然后采取key 。将其收集到List 。您现在拥有 List按计数排序的值。

现在只需使用 forEach打印它们。

如果仍在使用 Java 7,您可以使用 Map提供排序顺序:

final Map<String, Integer> counts = /*from somewhere*/
final List<String> sorted = new ArrayList<>(counts.keySet());
Collections.sort(sorted, new Comparator<String>() {

@Override
public int compare(final String o1, final String o2) {
return counts.get(o1).compareTo(counts.get(o2));
}
});

关于java - 如何从 .t​​xt 文件中读取字符串并根据出现次数将它们排序到 ArrayList 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24041875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com