[英]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.我承认这可能是一个简单的问题,但我似乎无法思考 map。 Say that I have a.txt file that I'm reading with a BufferedReader in Java that might look like this:假设我有一个 .txt 文件,我正在使用 Java 中的 BufferedReader 读取该文件,该文件可能如下所示:
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.例如,我想创建一个 HashMap,称为杂货,将 map 项目归入其各自的类别。 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?如何以跟踪哪个项目属于哪个类别的方式读取此文件,以便以有意义的方式将其放入 HashMap 中? 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) (我最初尝试使用 ArrayLists 但发现 HashMaps 可能比 map 数据更好)
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.这可以启发(在任何人关闭它之前):您要构建的结构是 map(键值结构)而不是列表。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.