在特定条件下保存对象的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());;
}
}

最新更新