使用 LinkedHashMap 计算出现次数

Count number of occurances using LinkedHashMap

我需要计算 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;
}

class 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);
        }
    }
}

我漏掉了一些我想不通的东西。

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

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

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;
}

P.S。我无法添加评论