How to compare two maps by their values

前端 未结 13 951
囚心锁ツ
囚心锁ツ 2020-12-08 12:09

How to compare two maps by their values? I have two maps containing equal values and want to compare them by their values. Here is an example:

    Map a = ne         


        
13条回答
  •  旧时难觅i
    2020-12-08 12:20

    The result of equals in your example is obviously false because you are comparing the map a with some values in it with an empty map b (probably a copy and paste error). I recommend to use proper variable names (so you can avoid these kinds of errors) and make use of generics, too.

        Map first = new HashMap();
        first.put("f"+"oo", "bar"+"bar");
        first.put("fo"+"o", "bar"+"bar");
    
        Map second = new HashMap();
        second.put("f"+"oo", "bar"+"bar");
        second.put("fo"+"o", "bar"+"bar");
    
        System.out.println("equals: " + first.equals(second));
    

    The concatenation of your strings doesn't have any effect because it will be done at compile time.

提交回复
热议问题