Question

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.

Was it helpful?

Solution

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

OTHER TIPS

The values in the map should be a one dimensional data structure as described in your problem statement. You're using ArrayList<Integer[]> which is a list of arrays, a 2D structure.

You want to map to multiple values? This is called a MultiMap!

I recommend this: Guava TreeMultiMap

basically your value is an arraylist of the values associated with that key.
All you'd have to do is include the guava library and it will be very neat and clean, instead of trying to create your own multimap implementation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top