Omen Omen - 3 months ago 8
Java Question

Map column values in TreeMap as key with line number as values

I want to read a column of numbers from a file in java. For example:

945
922
922
480
480
819
819
289
386


and I want to put these numbers in a
TreeMap
as keys. The value for each key will be the number of its line. Therefore, the map will have something like this:

{(945:1),(922:2,3),(480:4,5)}


I am trying the above, but I get an error.

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);
}


Could you please advise me?

Thanks.

Answer

Don't use ArrayList<Integer[]> because ArrayList itself is a container to hold your one dimensional line numbers, instead use like below:

TreeMap<Integer, ArrayList<Integer>> clusterMap = new TreeMap<Integer, ArrayList<Integer>>();

ArrayList will contain the line numbers of a given number in the file.

suppose current number is : num So check for the presence in the clusterMap:

if(clusterMap.containsKey(num )){
     clusterMap.get(num).add(lineNumber);
}
else{
    ArrayList<Integer> list = new ArrayList<>();
    list.add(lineNumber);
    clusterMap.put(num, list);
}
Comments