9/27/2023 0 Comments Declare hashmap javaIf both the maps are the same, then the equality check succeeds. Map> expectedMap = setupAddressObjectMap() ĪssertNotSame(expectedMap, actualEmployeeMap) ĪssertNotEquals(expectedMap, actualEmployeeMap) Otherwise, the checks will fail: //Comparing a Map> and Map> mapĪssertNotSame(employeeMap1, actualEmployeeMap) ĪssertNotEquals(employeeMap1, actualEmployeeMap) Map> employeeAddressMap1 = mUtil.createNestedMapfromStream(listEmployee) ĪssertNotEquals(employeeAddressMap1, actualEmployeeAddressMap) įor the Map with user-defined objects as values, we need to customize the equality method using one of the methods mentioned in the comparing HashMaps article. OuterBakedGoodsMap3.put("Donut", mUtil.buildInnerMap(batterList)) ĪssertNotEquals(outerBakedGoodsMap2, actualBakedGoodsMap) Similarly, if we change the outer Map‘s contents, the equality check will fail as well: assertNotEquals(outerBakedGoodsMap2, actualBakedGoodsMap) If the inner objects are all new instances every time in the case of user-defined objects, the equality check will also fail. If we change the inner Map's contents, the equality check fails. The default implementation compares each value. We can compare them using the equals() method. There are many ways to compare HashMaps in Java. In the second example, we are building an object of type >: Map> employeeMap = new HashMap() ĮmployeeMap = listEmployee.stream().collect(oupingBy((Employee emp) -> emp.getEmployeeId(),Ĭollectors.toMap((Employee emp) -> emp.getAddress().getAddressId(), fEmpObj -> fEmpObj.getAddress()))) collect(oupingBy(e -> e.getAddress().getAddressId(),Ĭollectors.toMap(f -> f.getAddress().getAddressLocation(), Employee::getEmployeeName))) We're then building a nested HashMap: Map> employeeAddressMap = listEmployee.stream() In the first example, the Employee has the Address object nested inside it. Here, we have two examples: one has an inner Map of Strings, and the other is a Map with Integer and Object values. If we have a List that we want to convert to a Map, we can create a stream and then convert it to a Map using the Collectors.toMap method.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |