0

I have a '|' delimited csv file with 2 columns:

A    |B
87657|5
87688|8
32134|4
...

I want to make a Map by reading this file, taking the column A values as string, and column B values as int.

I do (with delimiter = "|"):

    Map<String, Integer> output = new HashMap<>();
    assert delimiter.length() == 1;
    int count = 0;
    for(String line: Files.readAllLines(Paths.get(docidFreq), Charset.defaultCharset())) {
        count++;
        //skipping header row
        if (count == 1 ) {
            continue;
        }
        String tokens[] = line.split(delimiter);
        output.put(tokens[0], Integer.parseInt(tokens[1]));
    }
    return output;

However, the map contains single digit keys and values like (No relation to the sample file lines given above):

1:2
8:5
9:3
...

What am I doing wrong?

2
  • 2
    You should show us what delimiteris.. Commented Jan 9, 2015 at 10:35
  • @RC Sorry, edited. The delimiter is the string "|". Commented Jan 9, 2015 at 10:43

4 Answers 4

9

When you use the symbol '|' you have to escape it with two '\' like below in split.

split("\\|");
Sign up to request clarification or add additional context in comments.

Comments

0

Try something like:

String line = "87657|5";//line from a file
Map<String, Integer> map = new HashMap<String, Integer>();
String[] numbers = line.split("\\|");//assuming you have entries in file like "num1|num2"
map.put(numbers[0], Integer.parseInt(numbers[1]));
System.out.print(map);

Output:
{87657=5}

Comments

0

You can do something like:

StringTokenizer st = new StringTokenizer (line, "\\|");
map.put(st.nextToken(), Integer.parseInt(st.nextToken()));

Comments

0

You can use either any of following ways:

String[] str = line.split("\ \|");

or

StringTokenizer st = new StringTokenizer (line, "\ \|");

split() quite easy to use whereas StringTokenizer much faster than String.split() method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.