[英]How to iterate over object array from hashmap
我有兩個 hashmap 類型
Hashmap<String,Object[]> hasOne = new Hashmap<String,Object[]>();
Hashmap<String,Object[]> hasTwo = new Hashmap<String,Object[]>();
我在它們中都添加了值,
hasOne.put("anyKey", new Object[1,"Two",3.14]);
hasTwo.put("anyKey", new Object[1,"Two"]);
我的要求是我需要比較兩個哈希圖的 object 數組中的值,並且需要打印第二個 hashmap 中的object數組中的缺失數據(例如,比較new Object[1,"Two",3.14]
&& new Object[1,"Two"]
)。
使用Arrays.asList(hasOne.get("anyKey"));
// 將獲得 object 數組的詳細信息,但我不確定如何迭代該數組。
PFB 代碼片段
Map<String, Object[]> one = new HashMap<String, Object[]>();
Map<String, Object[]> two = new HashMap<String, Object[]>();
one.put("firstArray", new Object[] {1, "Two", 3.14});
two.put("secondArray", new Object[] {1, "Two"});
for(int k=0;k<one.size();k++)
{
System.out.println(Arrays.asList(one.get("firstArray")));
}
嘗試這個。 我使用的參考文獻是:
// create and insert into maps
Map<String, Object[]> one = new HashMap<String, Object[]>();
Map<String, Object[]> two = new HashMap<String, Object[]>();
one.put("firstArray", new Object[] {1, "Two", 3.14});
two.put("secondArray", new Object[] {1, "Two"});
for(int k=0;k<one.size();k++)
{
List<Object> arrList1 = new ArrayList<>(Arrays.asList(one.get("firstArray"))); // get the value from the map "one" as arrayList
List<Object> arrList2 = new ArrayList<>(Arrays.asList(two.get("secondArray"))); // get the value from the map "two" as arrayList
// System.out.println(arrList1 + " " + arrList2);
arrList1.removeAll(arrList2); // removes all different values as you require
System.out.println(arrList1);
}
我認為您的要求是,對於第一個 map 中的每個鍵,您希望在值數組中找到不在第二個 map 中的任何對象:
for (String entry: one.entrySet()) {
for (Object val: entry.getValue()) {
if (Arrays.stream(two.get(entry.getKey()).noneMatch(val::equals))) {
...
}
}
}
您可以在嵌套流中完成所有這些操作,但顯式for
循環更容易理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.