java - 在特定条件下保存对象的 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;
}
解决方案
我不确定下面的程序是否能解决您的需要 -
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());;
}
}
推荐阅读
- java - Intellij 拒绝将 Kotlin 目标 jvm 设置为 1.8?
- powerbi - 平均 使用客户 ID 和 Unix 纪元时间戳的事件之间的时间差(秒)
- kubernetes - 将清单文件应用于应用了水平自动缩放器的部署时,保持“幂等性”的最有效方法是什么?
- python - IndexError:使用 np.where() 时,用作索引的数组必须是整数(或布尔)类型
- python - Python Numpy - 将子数组与 4D 数组合并,无法让交换轴工作以构建 2D 全局数组
- location - 如何找到具有初始坐标和距离的新坐标?
- firebase - 在 Flutter 中启动获取 FCM 通知的服务或操作
- npm - 如何解决 Gulp 4.0 错误?
- kentico - 可以批准、拒绝和进行更改的工作流 API 角色仅列出
- autohotkey - 如何通过密钥但仅在一段时间后向下然后向上