我想从我拥有的两个数组中创建一个HashMap(Java)

时间:2015-10-19 19:00:29

标签: java arrays hashmap

现在我的程序正在输出我想要的数据(我用一些system.out.println语句检查了它)但我想将两个数组转换为包含两者的hashmap。我不知道如何去做。请帮忙!

这是我的代码:

import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;

public class Vending2 
{
  public static void main(String[] args) throws FileNotFoundException
  {
      System.out.print("Enter your food selection file: ");      // User inputs file
      Scanner input = new Scanner(System.in);                       // Keyboard input from user
      String filename = input.nextLine();
      Scanner fs = new Scanner(new File(filename));         // Scans in the file that was inputed

        String line;
        double price;
        int num = 0;
        while(fs.hasNextLine()){
             line = fs.nextLine();
             price = Double.parseDouble(line.split(":")[0]);
             num++;
        }

        fs.close();
        fs = new Scanner(new File(filename));

        double[] value = new double[num];                        //Array for prices
        int i = 0;
        while(fs.hasNextLine()){
             line = fs.nextLine();
             price = Double.parseDouble(line.split(":")[0]);
             value[i] = price;
             i++;
        }
        System.out.println(Arrays.toString(value));

        fs.close();
        fs = new Scanner(new File(filename));

         ArrayList<String> foods = new ArrayList<String>();  
        while( fs.hasNext()){

            String str = fs.nextLine();
            String words[] = str.split(":");
            if (words.length > 0){

                for(int j=1; j < words.length; j++){
                    foods.add(words[j]);
                }
            }
        }
        System.out.println("foods="+foods);


    }
  }

这是迄今为止输出的内容(这是我想要放入hashmap的内容):

1.0, 1.5, 1.5, 2.0, 1.0, 1.0, 1.25, 0.75, 1.0, 1.0, 1.0, 1.5, 1.25, 0.5, 0.5, 0.5, 3.5, 1.75, 0.25, 1.5]
foods=[Honey roasted peanuts, Cheetos, Bugles, Synder’s Pretzels, Snickers, Twix, M n Ms, Life savers, Twizzlers, Nutter Butters, Butter Fingers, King Size Kit Kats, Carrot sticks, Juicy Fruit, Spearmint Gum, Five gum, Pepperoni, Cheez-Its, Slim Jim, Lays Barbeque Chips]

2 个答案:

答案 0 :(得分:1)

如果您的两个数组/列表具有相同的长度,请执行以下操作:

Map<String, Double> map = new HashMap<>();
for (int i = 0; i < value.length; i++) {
    map.put(foods[i], value[i]);
    // or map.put(foods.get(i), value[i]) if foods is a List
}

假设一种食物只有一个价格。

答案 1 :(得分:1)

假设foods列表和value数组的长度始终相同,因此您可以将它们一起循环。

Map<String, Double> map = new HashMap<String, Double>();

int i = 0;
while (i < foods.size() && i < value.length) { //for safety i will check on both sizes
    map.put(foods.get(i), value[i]);
    i++;
}