【问题标题】:Count number of occurances using LinkedHashMap使用 LinkedHashMap 计算出现次数
【发布时间】:2016-03-23 19:42:06
【问题描述】:

我需要统计txt文件中相同字符串的出现次数。

我想出的是

public class CountWords {
public File file;
public Scanner scan = null;
public LinkedHashMap<String, Integer> list = new LinkedHashMap<>();

public CountWords(String txt) {
    file = new File(txt);
}

public void textEdit() {

    try {
        scan = new Scanner(file);
    } catch (FileNotFoundException e) {
        System.out.println("----");
    }

    while (scan.hasNextLine()) {
        String line = scan.nextLine();
        if(!list.containsKey(line))
            list.put(scan.next(),1);
        else {
            list.put(line,list.get(line)+1);
        }
    }
    scan.close();
}
public List<String> getResult(){
    textEdit();
    return list;
}

不应以任何方式更改 Main 类(这是要求) 并且输出的顺序应该与输入的顺序相同(这就是使用 LinkedHashMap 的原因)

public class Main {
    public static void main(String[] args) throws Exception {
        String fname = System.getProperty("user.home") + "/textforwords.txt";
        CountWords cw = new CountWords(fname);
        List<String> result = cw.getResult();
        for (String wordRes : result) {
            System.out.println(wordRes);
        }
    }
}

我错过了一些我无法弄清楚的东西。

【问题讨论】:

  • 这可以编译吗? getResult 被声明为返回一个列表,但您返回的是一个 LinkedHashMap。
  • @JimmyJames 不,这是我感到困惑的地方,我需要以某种方式连接这两件事,因为要求是“不要更改 Main”和“使用 LinkedHashMap”
  • getResult()返回的列表应该包含什么样的字符串?你有这方面的规范吗?

标签: java hashmap linkedhashmap


【解决方案1】:

您需要计算字符串或行数吗?

如果你需要计算字符串,试试这个:

while (scan.hasNext()) {
    String line = scan.next();
    if(!list.containsKey(line))
        list.put(line,1);
    else {
        list.put(line,list.get(line)+1);
    }
}

而getResult可以这样修改:

public List<String> getResult(){
    textEdit();

    ArrayList<String> result = new ArrayList<>();
    for(Map.Entry<String, Integer> entry : list.entrySet()){
        result.add(entry.getKey() + " " + entry.getValue());
    }
    return result;
}

附:我无法添加评论

【讨论】:

    猜你喜欢
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 2021-10-10
    • 1970-01-01
    相关资源
    最近更新 更多