com.github.siwenyan.common.MapComparer Maven / Gradle / Ivy
package com.github.siwenyan.common;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
//
//Compare two maps with same key type T and value type V
//
//@param
//@param
//
public class MapComparer {
private final Map left;
private final Map right;
//
//Constructor usage: provide a left map and a right map to compare
//Accept optional filters (regex expressions)
//
//@param left left
//@param right right
//@param keyFiltersInclude keyFiltersInclude
//
public MapComparer(Map left, Map right, String[] keyFiltersInclude) {
this.left = left;
this.right = right;
this.applyFilters(this.left, keyFiltersInclude);
this.applyFilters(this.right, keyFiltersInclude);
}
private void applyFilters(Map map, String[] keyFiltersInclude) {
if (null == keyFiltersInclude || keyFiltersInclude.length <= 0) {
return;
}
Set keysToBeRemoved = new HashSet();
for (T key : map.keySet()) {
boolean matches = false;
for (String filter : keyFiltersInclude) {
if (key.toString().matches(filter)) {
matches = true;
}
}
if (!matches) {
keysToBeRemoved.add(key);
}
}
for (T key : keysToBeRemoved) {
map.remove(key);
}
}
//
//Provide a compare result based on the left map
//
//@return Map
//
public Map> bareLeft() {
Map> reportList = new LinkedHashMap<>(this.left.size());
for (T key : this.left.keySet()) {
CompareReport report = new CompareReport();
report.setKey(key);
report.setExpectedValue(this.left.get(key));
report.setActualValue(this.right.get(key));
reportList.put(key, report);
}
return reportList;
}
//
//Provide a compare result based on the right map
//
//@return Map
//
public Map> bareRight() {
Map> reportList = new LinkedHashMap<>(this.left.size());
for (T key : this.right.keySet()) {
CompareReport report = new CompareReport();
report.setKey(key);
report.setExpectedValue(this.right.get(key));
report.setActualValue(this.left.get(key));
reportList.put(key, report);
}
return reportList;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy