java - 如何从 HashMap 中检索以前的值?

标签 java hashmap

我有以下代码,我正在从文本文件中读取内容。文本文件如下:

111 Laptop 500 10
222 Mobile 120 8
333 Notebook 4 100
444 Chocolates 3 50
555 Guitar 199 5
666 LenovoLaptop 470 10
777 HPLaptop 450 10
888 SonyVAIO 525 5

如果用户输入 ID 作为 111,则输出应如下:

111 Laptop 500 10
666 LenovoLaptop 470 10
777 HPLaptop 450 10
888 SonyVAIO 525 5

我将文本文件的内容存储在 HashMap 中。这是代码:

public void comparableItems(String ID)
{
    File f = new File("C://Class/items.txt");
    HashMap<String, Item> map = new HashMap<String, Item>();

    try
    {
        Scanner scan = new Scanner(f);

        while(scan.hasNext())
        {
            String line = scan.nextLine();
            String temp[] = line.split(" ");

            Item it = new Item(temp[0], temp[1], Double.parseDouble(temp[2]), Integer.parseInt(temp[3]));

            map.put(it.itemID, it);
        }
        if(map.containsKey(ID))
        {
            Item item = map.get(ID);
            if(item.price>=item.price+100 && item.price<=item.price-100)
            {

            }
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}

这是 Item 类:

public class Item 
{
String itemID;
String itemName;
double price;
int quantity;

public Item(String itemID, String itemName, double price, int quantity)
{
    this.itemID = itemID;
    this.itemName = itemName;
    this.price = price;
    this.quantity = quantity;
}

public void printItemDetails()
{
    System.out.println("ID\tItemName\tUnitPrice\tQuantity");
    System.out.println("===================================================");

    System.out.println(this.itemID+ "\t" +this.itemName+ "\t" +this.price+ "\t"+this.quantity);
}
}

如何获得所需的输出?我正处于 Java Collections 的学习阶段。所以请耐心等待。

有人可以帮我吗?

谢谢!

最佳答案

您的 map 对您没有多大帮助。由于您在解析文件之前就知道要查找的引用项 ID,因此您可以在解析过程中看到该项目(如果)时捕获该项目。您确实需要某种集合来保存所有其他项目,但 List 对于此特定任务来说是更好的选择。

无论如何,您的问题的主旨似乎是检查您从文件中解析的所有其他项目。为此,您需要迭代 Mapvalues() View (并进行正确的比较):

for (Item otherItem : map.values()) {
    if((otherItem.price <= item.price + 100)
            && (otherItem.price >= item.price - 100)) {
        otherItem.printItemDetails();
    }
}

如果您在 List 而不是 Map 中收集了项目,那么您可以将上面的 map.values() 替换为只是list(或者您为List使用的任何名称)。

关于java - 如何从 HashMap 中检索以前的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30514520/

相关文章:

Java 正则表达式识别 Github 中错误的引用

java - Hashmap get(key) 即使值存在也返回 null

java - 从文件加载大 HashMap<String, TreeMap> 会给出 java.lang.OutOfMemoryError(超出 GC 开销限制)

c++ - Unordered_map 或 hashMap 现有散列函数修改?

Java HashMap 实现哈希码问题

java - 将文档映射到以 'is' 开头的 Java 对象

java - 如何使用 Log4j2 使用 map 查找?

java - 将触摸事件从回收器传递到其父 LinearLayout

java - 将对象数组传递给方法

java - 如何在 Java 中迭代 HashMap 值时替换它们