简体   繁体   中英

How to store String type of array values in to HashMap object

When i try to store String array value to the hashmap it will show null value.please give any solution.thanks in advance

                String temp;
                String[] line=new String[15];
                Map<String, String> map=new HashMap<String, String>();

                InputStream stream=new FileInputStream(path);
BufferedReader reader =new BufferedReader(new InputStreamReader(stream));
                while((temp = reader.readLine()) != null)
                {
                    for(int j=0; j<line.length ;j++)
                    {   
                        line[j]=reader.readLine();

                        String fname=line[0];
                        String lname=line[1];
                        String mobile=line[2];
                        String gender=line[3];

                    //Store array string to map
                        map.put("fname",fname);

                    //retrive map object    
                       System.out.println(map.get(fname));

                System.out.println(fname);//showing null value in console

                System.out.println(lname);//array shows values
                System.out.println(mobile);//array shows values

                    }

You tried to get map value by value (variable fname)

 System.out.println("map.get(fname) = "+map.get(fname));

but you should use map.get(key) and your key is "fname" (as a string) and not fname (as a variable)

the solution is

System.out.println("map.get(fname) = "+map.get("fname"));

and for FileInputStream try to use file instead of path :

 File file = new File("C:/*****");
 InputStream stream=new FileInputStream(file);

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