首页 > 解决方案 > 在特定条件下保存对象的 HashMap 值时出错

问题描述

我想保存 HashMap_products中低于某个价格的所有值,但由于某种原因,我在执行此操作时遇到错误,我不明白,我做错了什么?

我对java很陌生,所以有没有更有效的方法来做到这一点?

public class Product implements Serializable {
    private String _key;
    private String _supplier_key;
    private int _price;
    private int _critical_value;
    private int _stock;

    public Product(String key, String supplier_key, int price, int critical_value, int stock) {
        _key = key;
        _supplier_key = supplier_key;
        _price = price;
        _critical_value = critical_value;
        _stock = stock;
    }

    public String getId() {
        return _key;
    }

    public int getPrice() {
        return _price;
    }

    public void setPrice(int price) {
        _price = price;
    }

    @Override
    @SuppressWarnings("nls")
    public String toString() {
        String str = String.format("%s|%s|%d|%d|%d", _key, _supplier_key, _price, _critical_value, _stock);
        return str;
    }
}

private Map<String, Product> _products = new HashMap<String, Product>();

public String showProductsPrice(int price) {
    String str = "";

    for (Map.Entry<String, Product> entry : _products.entrySet())
        if (entry.getValue().getPrice() < price)
            str+=entry.getValue().toString() + '\n';

    return str;
}

标签: javahashmap

解决方案


我不确定下面的程序是否能解决您的需要 -

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;

public class Product implements Serializable {
    private String _key;
    private String _supplier_key;
    private int _price;
    private int _critical_value;
    private int _stock;

    public Product(String key, String supplier_key, int price, int critical_value, int stock) {
        _key = key;
        _supplier_key = supplier_key;
        _price = price;
        _critical_value = critical_value;
        _stock = stock;
    }

    public String getId() {
        return _key;
    }

    public int getPrice() {
        return _price;
    }

    public void setPrice(int price) {
        _price = price;
    }

    @Override
    @SuppressWarnings("nls")
    public String toString() {
        String str = String.format("%s|%s|%d|%d|%d", _key, _supplier_key, _price, _critical_value, _stock);
        return str;
    }

    public static void main(String args[]){
        System.out.println("**********");
        Map<String, Product> products = new HashMap<String, Product>();
        IntStream.range(1,11).forEach(i -> {
            products.put(""+i, new Product(""+i,"sk"+i, i, i,i+1));
        });
        showProductsPrice(7, products);

    }

    public static void showProductsPrice(int price, Map<String, Product> _products) {
        for (Map.Entry<String, Product> entry : _products.entrySet())
            if (entry.getValue().getPrice() < price)
                System.out.println(entry.getValue());;
    }
}

推荐阅读