简体   繁体   中英

reading CSV file into hashmap

I have a CSV file which contain fields as follows: Field 1, Field 2,Field 3, the frequency , and I want to assign it to hash map variable in Java. the code below from here is to scan the file and calculate the frequency for each line, However I have the file with frequencies already so I just need to read a few lines. so I replace

    // split the transaction into items

with

        String[] lineSplited = line.split(" "); 
        String itemString = lineSplited[0];
        Integer count = Integer.valueOf(lineSplited[1]);
        mapSupport.put(itemString, count);

in the original code

private void DetermineFrequencyOfSingleItems(String input,
            final Map<String, Integer> mapSupport)
            throws FileNotFoundException, IOException {
        //Create object for reading the input file
        BufferedReader reader = new BufferedReader(new FileReader(input));
        String line;
        // for each line (transaction) until the end of file
        while( ((line = reader.readLine())!= null)){ 
            // if the line is  a comment, is  empty or is a
            // kind of metadata
            if (line.isEmpty() == true ||
                    line.charAt(0) == '#' || line.charAt(0) == '%'
                            || line.charAt(0) == '@') {
                continue;
            }

            // split the transaction into items
            String[] lineSplited = line.split(" ");
             // for each item in the transaction
            for(String itemString : lineSplited){ 
                // increase the support count of the item
                Integer count = mapSupport.get(itemString);
                if(count == null){
                    mapSupport.put(itemString, 1);
                }else{
                    mapSupport.put(itemString, ++count);
                }
            }
            // increase the transaction count
            transactionCount++;
        }
        // close the input file
        reader.close();
    } 

but it does not work, any suggestion?

In the original program, the line frequency is counted so the CSV lines are split using " "(space) makes no difference.

But since you are reading the data, you have to split using "," (comma) and trim the String before using as key in your map or parsing as Integer.

And please be specific about your problem and what kind of error you get.

Since your file is tab spaced and you want the last field as count and rest as the key value, try

String frequency = line.substring(line.lastIndexOf('\t')+1);// Parse as Integer 
String key=line.substring(0, line.lastIndexOf('\t'));
mapSupport.put(key,Integer.parseInt(frequency));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM