pankaj kashyap pankaj kashyap - 1 month ago 14
Java Question

HashMap individual value retrieval in Java

I have created a

HashMap
listed below:

Map<String, List<Double>> hm1 = new HashMap<String, List<Double>>();
List<Double> hmValues1 = new ArrayList<Double>();


and using this below method to add values from a file, where the specified values of the file are:

line1 0.418 0.24968 -0.41242 0.1217 0.34527 -0.044457 -0.49688 -0.17862 0.00066023 -0.6566
line2 0.013441 0.23682 -0.16899 0.40951 0.63812 0.47709 -0.42852 -0.55641 -0.364 -0.23938
line3 -0.418 -0.24968 0.41242 -0.1217 -0.34527 -0.16899 -0.40951 -0.63812 -0.47709 0.42852


I am able to print all the values of key:
line1
, but I want to retrieve individual values of the list, to process them separately.

public static void conceptHashMap() {
int len,i=0;
double dVal=0.0;
String strLine;
String conceptSearch = "line1"; // will be a key in hashmap

try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {

while ((strLine = br.readLine()) != null) {
String[] dims = strLine.split(" ");
len = dims.length;
if (dims[i++].equals(conceptSearch)) {
while (--len>0) {
dVal=Double.parseDouble(dims[i++]);
hmValues1.add(dVal);
}
hm1.put(conceptSearch, hmValues1);
for (Map.Entry<String, List<Double>> entry : hm1.entrySet()) {
String key = entry.getKey();
List<Double> hmvalues1 = entry.getValue();
System.out.println("key value pair");
System.out.println("Key = " + key);
System.out.println("Values = " + hmvalues1);
}
break;
}
i=0;
}
} catch (IOException e) {
e.printStackTrace();
}
}

Answer
public static void conceptHashMap() {
int len,i=0;
double dVal=0.0;
String strLine;
String conceptSearch = "line1";     // will be a key in hashmap

try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {

    while ((strLine = br.readLine()) != null) {
        String[] dims = strLine.split(" ");
        len=dims.length;
        if(dims[i++].equals(conceptSearch)){
            while(--len>0) {
                dVal=Double.parseDouble(dims[i++]);
                hmValues1.add(dVal);
            }
            hm1.put(conceptSearch, hmValues1); 
            for (Map.Entry<String, List<Double>> entry : hm1.entrySet()) {
                String key = entry.getKey();
                List<Double> hmvalues1 = entry.getValue();
                System.out.println("key value pair");
                System.out.println("Key = " + key);
                System.out.println("Values = " + hmvalues1);
                // simply iterate the list to get each single value 
                for(Double hmvalue : hmvalues1){
                      System.out.println(hmvalue);
                }

            }
            break;  
        }
        i=0; 
    }
} catch (IOException e) {
    e.printStackTrace();
    }
}

You can simple get each value in list and do whatever you need it for.