问题描述
我是收藏的新手。我需要知道如何使用带有两个条目的 ArrayList。 我正在编写一个程序,该程序读取文件并将字符串存储到树状图中,并将字符串与具有两列(文档 ID、计数)的 ArrayList 相关联。我想知道我怎么能做到这一点。有人可以帮助我提供有关如何执行此操作的指导吗?以下是系统应该如何工作:
例如: 如果程序读取到单词“Hello”,则需要将单词作为 Treemap("Hello",Arraylist) 添加到树状图中。
Hello 一词与 ArrayList 中的 (DocumentID,Count) 相关联。
解决方法
在 arraylist 中,我们不能存储在键值对中,因此您可以使用 pair 代替 arrayList。
Pair
您不能将两个值放入一个 ArrayList。您可以创建一个新类来存储 documentId 和计数。然后将这个新类存储在 TreeMap 的 List 中:
public class CountPerDocument {
private final String documentId;
private final int count;
CountPerDocument(String documentId,int count){
this.documentId = documentId;
this.count = count;
}
public String getDocumentId() {
return documentId;
}
public int getCount() {
return count;
}
}
然后像这样填充你的地图
Map<String,List<CountPerDocument>> map = new TreeMap<>();
List<CountPerDocument> list = new ArrayList<>();
//add code to fill your list here
list.add(new CountPerDocument("yourId",23));
map.put("term",list);