如何从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"]);

我的要求是,我需要比较两个哈希图的对象数组中的值,并需要打印第二个哈希图对象数组中缺少的数据(例如,在比较new Object[1,"Two",3.14]&&new Object[1,"Two"]时,第二个数组中缺少3.14(。

使用Arrays.asList(hasOne.get("anyKey"));//将获得对象数组的详细信息,但我不确定如何迭代该数组。

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")));
}

试试这个。我使用的参考文献有:

  1. https://www.javatpoint.com/how-to-compare-two-arraylist-in-java
  2. 为什么在尝试从列表中删除元素时会出现UnsupportedOperationException
// 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);
}

我认为您的要求是,对于第一个映射中的每个键,您都希望在值数组中找到第二个映射中没有的任何对象:

for (String entry: one.entrySet()) {
for (Object val: entry.getValue()) {
if (Arrays.stream(two.get(entry.getKey()).noneMatch(val::equals))) {
...
}
}
}

您可以在嵌套流中完成所有这些操作,但显式for循环更容易理解。

最新更新