-1

I have two hashmap of type

Hashmap<String,Object[]> hasOne = new Hashmap<String,Object[]>();
Hashmap<String,Object[]> hasTwo = new Hashmap<String,Object[]>();

I've added values in both of them,

hasOne.put("anyKey", new Object[1,"Two",3.14]);
hasTwo.put("anyKey", new Object[1,"Two"]);

My requirement is I need to compare values from the object array of both hashmaps and need to print missing data from the object array of the second hashmap ( Ex. 3.14 is missing in the second array on comparing new Object[1,"Two",3.14] && new Object[1,"Two"] ).

Using Arrays.asList(hasOne.get("anyKey"));// will get details of object array but i'm not sure how to iterate over that array.

PFB code snippet

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")));
}
Sankalp
  • 3
  • 1
  • By the way, your use of an array of `Object` smells like a design problem that should be addressed by defining a class. Java 16 makes this easier with its [records](https://openjdk.java.net/jeps/395) feature if the main purpose of your class is to communicate data transparently and immutably. – Basil Bourque May 26 '21 at 05:00

2 Answers2

1

Try this. References I used are :

  1. https://www.javatpoint.com/how-to-compare-two-arraylist-in-java
  2. Why do I get an UnsupportedOperationException when trying to remove an element from a List?
        // 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);
        }
0

I think your requirement is that for each key in the first map you want to find any objects in the value array which are not in the second map:

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

You can do all this in nested streams but explicit for loops are easier to understand.

sprinter
  • 27,148
  • 6
  • 47
  • 78