gpt4 book ai didi

java - 获取HashMap值的count个数

转载 作者:行者123 更新时间:2023-11-30 02:55:34 25 4
gpt4 key购买 nike

使用此 link 中的代码将文本文件内容加载到 GUI:

Map<String, String> sections = new HashMap<>();
Map<String, String> sections2 = new HashMap<>();
String s = "", lastKey="";
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
while ((s = br.readLine()) != null) {
String k = s.substring(0, 10).trim();
String v = s.substring(10, s.length() - 50).trim();
if (k.equals(""))
k = lastKey;
if(sections.containsKey(k))
v = sections.get(k) + v;
sections.put(k,v);
lastKey = k;
}
} catch (IOException e) {
}
System.out.println(sections.get("AUTHOR"));
System.out.println(sections2.get("TITLE"));

如果 input.txt 的内容为:

AUTHOR    authors name
authors name
authors name
authors name
TITLE Sound, mobility and landscapes of exhibition: radio-guided
tours at the Science Museum

现在我想计算 HashMap 中的值,但是 sections.size() 计算存储在文本文件中的所有数据行。

我想问一下如何计算项目,即sections中的值v?如何根据作者姓名获得编号4

最佳答案

由于作者具有一对多关系,因此您应该将其映射到 List 结构而不是 String

例如:

Map<String, ArrayList<String>> sections = new HashMap<>();
Map<String, String> sections2 = new HashMap<>();
String s = "", lastKey="";
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
while ((s = br.readLine()) != null) {
String k = s.substring(0, 10).trim();
String v = s.substring(10, s.length() - 50).trim();
if (k.equals(""))
k = lastKey;

ArrayList<String> authors = null;
if(sections.containsKey(k))
{
authors = sections.get(k);
}
else
{
authors = new ArrayList<String>();
sections.put(k, authors);
}
authors.add(v);
lastKey = k;
}
} catch (IOException e) {
}

// to get the number of authors
int numOfAuthors = sections.get("AUTHOR").size();

// convert the list to a string to load it in a GUI
String authors = "";
for (String a : sections.get("AUTHOR"))
{
authors += a;
}

关于java - 获取HashMap值的count个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37291618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com