我想从 java 文件中读取一列数字。例如:
945
922
922
480
480
819
819
289
386
我想将这些数字作为键放入 TreeMap
中。每个键的值将是其行号。因此, map 将具有如下内容:
{(945:1),(922:2,3),(480:4,5)}
我正在尝试上述操作,但出现错误。
ArrayList<Integer> clusterNums = new ArrayList<>();
String clusterLine;
TreeMap<Integer, ArrayList<Integer[]>> clusterMap = new TreeMap<Integer, ArrayList<Integer[]>>();
while ((clusterLine = clusterFile.readLine()) != null) {
clusterNums.add(Integer.parseInt(clusterLine));
}
for (int i = 1; i < clusterNums.size(); i++){
if (!clusterMap.containsKey(clusterNums.get(i-1))) {
clusterMap.put(clusterNums.get(i-1), new ArrayList<Integer[]>());
}
clusterMap.get(clusterNums.get(i-1)).add(i);
}
你能给我点建议吗?
谢谢。
最佳答案
不要使用 ArrayList<Integer[]>
因为ArrayList
本身就是一个容器来容纳你的一维line numbers
,而是像下面这样使用:
TreeMap<Integer, ArrayList<Integer>> clusterMap = new TreeMap<Integer, ArrayList<Integer>>();
ArrayList
将包含文件中给定数字的行号。
假设当前号码是:num
所以检查 clusterMap
中是否存在:
if(clusterMap.containsKey(num )){
clusterMap.get(num).add(lineNumber);
}
else{
ArrayList<Integer> list = new ArrayList<>();
list.add(lineNumber);
clusterMap.put(num, list);
}
关于java - 将 TreeMap 中的列值映射为键,以行号作为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19986452/