我创建了下面列出的HashMap
:
Map<String, List<Double>> hm1 = new HashMap<String, List<Double>>();
List<Double> hmValues1 = new ArrayList<Double>();
并使用以下方法从文件中添加值,其中文件的指定值为:
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
我能够打印密钥的所有值:line1
,但我想检索列表的各个值,以便单独处理它们。
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();
}
}
答案 0 :(得分:0)
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();
}
}
您可以简单地获取列表中的每个值并执行您需要的任何操作。