How to compare two hashmaps in java?

前端 未结 4 1845
眼角桃花
眼角桃花 2020-12-06 15:50

I have two hash maps like the following:

1.=============Employee=================


Key : 1_10 : Value : 13/04/2012
Key : 1_11 : Value : 18/04/2012
Key : 1_         


        
相关标签:
4条回答
  • 2020-12-06 16:20

    below is the code which works perfectly, the reason why the comparison failed is the map value is different .

    Key : 27 : Value : 27/4/2012, Key : 1_18 : Value : 27/04/2012
    

    if we see the dates, the difference is clearly seen. 27/4/2012 is different from 27/04/2012 since i stored it as a string.

    Iterator<Map.Entry<String,String>> holyDayiterator = workingdayMap.entrySet().iterator();
    
                     while (holyDayiterator.hasNext()) {
                        Map.Entry holiDayEntry = holyDayiterator.next();
                        if(!employeeMap.containsValue((holiDayEntry.getValue()))){
                            System.out.println("works perfect");
                        }
    

    Thanks guys for your support and people who have gave down vote also.

    :) Tony

    0 讨论(0)
  • 2020-12-06 16:34

    Are the Values Date objects? If so you're attempting to see if the map contains the same object (well its hash, which will be different unless you stored the EXACT same instance in both maps) rather than the value of the object.

    0 讨论(0)
  • 2020-12-06 16:38

    Can you please try like this.

        HashMap<String, Date> employeeMap = new HashMap<String, Date>();
    
        HashMap<String, Date> workingdaymap = new HashMap<String, Date>();
    
        Set<String> values1 = new HashSet<String>(employeeMap.values());
        Set<String> values2 = new HashSet<String>(workingdaymap.values());
        boolean equal = values1.equals(value2);
    
    0 讨论(0)
  • 2020-12-06 16:39

    Something like this should work:

    Set workingValues = new HashSet(workingdayMap.values());
    workingValues.removeAll(employeeMap.values());
    

    We get all the values out of workingdayMap using the values() method. We don't want to modify this Collection directly as this will modify workingdayMap so we create a Set of our values called workingValues.

    We then remove all the values found in employeeMap which will leave the values which are in workingdayMap but not in employeeMap in workingValues.

    0 讨论(0)
提交回复
热议问题