Parsing a text file using HashMap and List

I have a text file like:

fruits bananna blackbery apple
vegetable carrot potato
cars toyota honda ww bmw

I need my Java program to take a type string vegetableand display the following words in a string. In this case, the program will displaycarrot potato

I have the code below:

public static void ParseWithHashMap(String wordGiven) throws IOException {

        HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
        ArrayList<String> lemmes = new ArrayList<String>();

        FileInputStream fin = null;
        InputStreamReader isr = null;
        BufferedReader br = null;

        try {
            fin = new FileInputStream("test.txt");
            isr = new InputStreamReader(fin, "UTF-8");
            br = new BufferedReader(isr);
            String line = br.readLine();

            while (line != null) {
                String[] toks = line.split("\\s+");

                for (int i = 1; i < toks.length; i++) {
                    lemmes.add(toks[i]);

                }
                map.put(toks[0], lemmes);
                line = br.readLine();

            }
        } finally {

        }

        System.out.println(map.get(wordGiven));
    }

The problem is that when you enter the fruitsprogram will display all the words from the text file, except for the first word of each line

bananna blackbery apple carrot potato toyota honda ww bmw

and I want to show me the words that follow the word that I give, in this case it would be

bananna blackbery apple

What am I doing wrong?

+3
source share
2 answers

You need to declare / define yours ArrayListin the while loop while (line != null) {.

, , , . , .

,

  while (line != null) {
       ArrayList<String> lemmes = new ArrayList<String>();
       ...

.

+4

List#clear arraylist map .

map.put(toks[0], lemmes);
lemmes.clear();
+1

All Articles