Home > Software engineering >  Guava getting one map for differences
Guava getting one map for differences

Time:07-28

I'm using guava to compare two JSON files together and have done the following:

ObjectMapper mapper = new ObjectMapper();
TypeReference<HashMap<String, Object>> type = 
    new TypeReference<HashMap<String, Object>>() {};

Map<String, Object> leftMap = mapper.readValue(leftJson, type);
Map<String, Object> rightMap = mapper.readValue(rightJson, type);

MapDifference<String, Object> difference = Maps.difference(leftMap, rightMap);
System.out.println(difference.entriesDiffering());

Output

package=([{Name=Sarah}], [{Name=Conor}])

Expected output

package=([{Name=Conor}])

Does anyone know how to manipulate the output to just show one side?

CodePudding user response:

I assume that you want to end up with another Map<String,Object>, but taking the value of keys with differing values from the right (or maybe the left, you don't say).

import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;

import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        Map<String, Object> left = Map.of("name", "sarah");
        Map<String, Object> right = Map.of("name", "connor");
        MapDifference<String, Object> result = Maps.difference(left, right);
        Map<String,Object> f = result.entriesDiffering().entrySet().stream()
                .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().rightValue()));
        System.out.println(f);
    }
}

CodePudding user response:

MapDifference#entriesDiffering() returns Map<K,​MapDifference.ValueDifference<V>>, so please read ValueDifference and make use of its API.

Here's a sample MRE:

@Test
public void shouldShowDifferences() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    TypeReference<HashMap<String, Object>> type =
            new TypeReference<HashMap<String, Object>>() {};

    String leftJson = "{\"package\": [{\"Name\": \"Sarah\"}]}";
    String rightJson = "{\"package\": [{\"Name\": \"Connor\"}]}";
    Map<String, Object> leftMap = mapper.readValue(leftJson, type);
    Map<String, Object> rightMap = mapper.readValue(rightJson, type);

    MapDifference<String, Object> difference = Maps.difference(leftMap, rightMap);
    System.out.println(difference.entriesDiffering());
    // {package=([{Name=Sarah}], [{Name=Connor}])}
    difference.entriesDiffering().forEach(
            (key, valueDifference) -> System.out.printf(
                    "key: '%s'; values: left: '%s', right: '%s'",
                    key, valueDifference.leftValue(), valueDifference.rightValue()));
    // key: 'package'; values: left: '[{Name=Sarah}]', right: '[{Name=Connor}]'
}
  • Related