gpt4 book ai didi

java - 在没有比较器、数组列表或树集的情况下对映射进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 12:40:29 24 4
gpt4 key购买 nike

存储在网页上找到的单词并将其与其出现次数进行映射后,您将如何按频率(从最高到最低)对它们进行排序?

我可以访问的唯一导入是 Arrays、HashMap、HashSet、Map 和 Set。我研究了如何做到这一点,但似乎大多数人建议使用比较器或迭代器,我不想实现。

map 设置如下:Map found = new HashMap<>();

这是我到目前为止所拥有的:

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import util.WebDoc;

public class Sorting{

public static void main(String[] args) throws IOException {
String url;

url = “INSERT URL HERE”;

final int numPairs = 30; // maximum number of pairs to print

// get body of the web document
String content = WebDoc.getBodyContent(url);
String word_pattern = "[A-Za-z]{5,}";
Map<String, Integer> found = new HashMap<>(); // (word,frequency)

Matcher match = Pattern.compile(word_pattern).matcher(content);
int unique = 0;
while (match.find()) {
String word = match.group().toLowerCase();

System.out.println(word);

if (found.containsKey(word)){
if (found.get(word)==1)
unique--;
found.put(word, found.get(word) +1);
}
else{
found.put(word, 1);
unique++;
}
}
}

最佳答案

如果您改变了使用基本 JDK 实用程序的想法,这里有一种使用流的方法:

List<String> sorted = found.entrySet()
.stream()
.sort(Comparator.comparing(Map.Entry::getValue).reversed())
.map(Map.Entry::getKey)
.collect(Collectors.toList());

关于java - 在没有比较器、数组列表或树集的情况下对映射进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36879295/

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