簡體   English   中英

迭代 Hashmap 中的值列表

[英]Iterate over a list of values within a Hashmap

詞法分析程序:用一個文本文件,將每個標記分離到關鍵字、字符、數字、整數等類別下。

所以我創建了一個 hashMap,其中散列圖中的每個鍵都必須以某種方式進行隔離,即 Keyword = [if, then, else], Special = [(,),.,;], Character = [a,b, c],所以每個鍵都有自己的列表。

但我還需要計算每個標記在文本文件中出現的次數,所以我想遍歷每個單獨的列表並在那里找到每個單詞/字符/數字的出現次數,但是這絕對是很多錯誤的代碼,因為我想不出比 list.contains(word) count++ 更好的方法,並且對每個單詞/字符/數字都這樣做。


import java.io.*;
import java.util.*;

public class Main {

    private static HashMap<String, ArrayList<String>> map;
    private static ArrayList<String> keys;
    private static ArrayList<String> special;
    private static ArrayList<String> characters;
    private static ArrayList<String> integers;
    private static ArrayList<String> digits;
    private static Token k;

    public static void main(String[] args) {

        map = new HashMap<>();
        keys = new ArrayList<>();
        special = new ArrayList<>();
        characters = new ArrayList<>();
        integers = new ArrayList<>();
        digits = new ArrayList<>();
        k = new Token();

        executeAnalysis();
    }

    private static void executeAnalysis() {
        try {
            File file = new File("/Users/karinaabad/Desktop/HW311.txt");
            Scanner scanner = new Scanner(file);

            while(scanner.hasNext()) {
                String w = scanner.next();
                segregateTokens(w);
            }
            printSummary();
        } catch (FileNotFoundException f) {
            System.out.println("Invalid file input.");
        }
    }

    private static void segregateTokens(String w) {
        if (k.checkKeyword(w))
        {
            keys.add(w);
        }

        if (k.checkSpecial(w)) {
            special.add(w);
        }

        if (k.checkDigit(w)) {
            digits.add(w);
        }

        if (k.checkIntegers(w)) {
            integers.add(w);
        }

        if (k.checkCharacters(w)) {
            characters.add(w);
        }

        map.put("Keyword", keys);
        map.put("Special", special);
        map.put("Digit", digits);
        map.put("Integers", integers);
        map.put("Characters", characters);
    }

    private static void printSummary() {
        System.out.println("==========Summary Report==========");
        for (Map.Entry<String, ArrayList<String>> pair : map.entrySet())
        {
            System.out.println(pair.getKey() + " : " + pair.getValue());
        }
    }

    private static void checkCount() {
        for (Map.Entry<String, ArrayList<String>> key : map.entrySet()) {
            for (String value : )
        }
    }
}

println()調用在循環完成后(在包含整數的行的末尾println()打印一個換行符。

如果println()不存在並且代碼嘗試打印其他內容,它將與整數出現在同一行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM