我有两个哈希图,一个包含键,另一个包含具有对象值的键。
这是我的两张地图及其价值
第一个是:
newProdList = [18 =,2 =,21 = 1099887,5 =,22 = 1099888,7 =,14 =]
第二个是:
oldList = [2 =库存[location = AAQ-08-2,stockQty = 150, productCode = null,productName =紧急男式跑鞋, 部门=鞋子,类别=跑步,3 =库存[位置= AAR-01-1, stockQty = 192,productCode = 19234402,productName =男士跑步鞋 19234402,部门=鞋子,类别=跑步],4 =库存 [location = BAN-08-1,stockQty = 190,productCode = 19108206, productName = Carson 2 New Core男士慢跑鞋,部门=鞋子, category = Running],21 = Stock [location = BAN-08-1,stockQty = 190, productCode = 19108206,productName = Carson 2 New Core男子跑步 鞋,部门=鞋,类别=跑步]]
我想迭代newProductList并在oldList中使用其中的键来生成对象列表。
这很简单:
List<Stock> stocks = new ArrayList<>();
for(Entry<?, ?> e: newProductList.entrySet()){
Stock s = (Stock) oldProdList.get(e.getKey());
stocks.add(s);
}
System.out.println(stocks);
但是我想使用Stream api。
答案 0 :(得分:1)
由于您仅使用newProductList
的键,因此建议您在keySet()
上进行迭代。
然后您可以执行以下操作:
List<Stock> stocks = newProductList.keySet().stream() //stream over the keys
.map(oldProdList::get) //map by calling get() on the old list
.filter(Objects::nonNull) //remove nulls
.collect(Collectors.toList()); //build the result list
这里我们遍历键,通过查找来映射它们,过滤非空结果(以防查找失败)并收集结果。
答案 1 :(得分:0)
遍历entrySet以从oldList中的newProdList获取相应的密钥,并从newProdList中的oldList的该条目中设置值。
在此处详细了解地图Entry
Map<String,String> newProdList = new HashMap<>();
newProdList.put("18", null);
newProdList.put("2", null);
newProdList.put("21", "1099887");
newProdList.put("5", null);
newProdList.put("22", "1099888");
newProdList.put("7", null);
newProdList.put("14", null);
Map<String,String> oldList = new HashMap<>();
oldList.put("2", "Stock [location=AAQ-08-2, stockQty=150, productCode=null, productName=Emergence Men's Running Shoes, division=Shoes, category=Running]");
oldList.put("3", "Stock [location=AAR-01-1, stockQty=192, productCode=19234402, productName=Men's Running Shoes 19234402, division=Shoes, category=Running]");
oldList.put("4", "Stock [location=BAN-08-1, stockQty=190, productCode=19108206, productName=Carson 2 New Core Men?s Running Shoes, division=Shoes, category=Running]");
oldList.put("21", "Stock [location=BAN-08-1, stockQty=190, productCode=19108206, productName=Carson 2 New Core Men?s Running Shoes, division=Shoes, category=Running]");
newProdList.entrySet().stream().forEach(e -> e.setValue(oldList.get(e.getKey())));
根据要求提供有关此精美架构的更多说明。