繁体   English   中英

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

[英]I want to create a HashMap out of two arrays that I have (Java)

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

这是我的代码:

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);


    }
  }

这是到目前为止输出的内容(这是我想放入哈希图中的内容):

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]

假设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++;
}

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

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
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM