简体   繁体   中英

How do I read in a file such that for each line that contains a certain string, save the lines underneath to a HashMap?

I admit this might be a simple question but I cannot seem to map my head around it. Say that I have a.txt file that I'm reading with a BufferedReader in Java that might look like this:

Category: Dairy
Yogurt
Cheese
Butter
Category: Vegetables
Carrots
Cucumbers
Category: Snacks
Granola Bars
Trail Mix
Chips
Candy
Pop Tarts

I want to create a HashMap, for example, called groceries that will map the items to its respective category. For example:

groceries.put("item", "category");

How do I read this file in such a way that keeps track of which item belongs to which category so I can place it into the HashMap in a meaningful way? Here is a rough idea of what I have tried so far. (I tried initially with ArrayLists but figured out HashMaps might be better to map the data)

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = in.readLine()) != null) {
            if (line.contains("Category")){
                
                  (save in an arrayList() called Category)

            }
            else{
                  (save in arrayList() called Item)
            }
        }

Again that is just what I had originally tried. Let me know if any further clarification is needed.

This can inspire (before anyone closes it ): The structure you want to build is a map (key-value structure) not a list.

BufferedReader in = new BufferedReader(new InputStreamReader(System.in)));
String line;
String currentCategory = "";
Map<String, String> groceries = new HashMap<>();
while ((line = in.readLine()) != null) {
    if (line.startsWith("Category: ")) {
        currentCategory = line.substring(10);
    } else {
        groceries.put(line, currentCategory);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM