unknown_boundaries
unknown_boundaries

Reputation: 1590

Map same key and value using google collections

I need to validate if map (String to String) entry doesn't contain same key and value pair (case-insensitive). For example -

("hello", "helLo") // is not a valid entry

I was wondering if Google collection's Iterable combined with Predicates some how could solve this problem easily.

Yes I could have simple iterator for entries to do it myself, but thinking of any thing already up.

Looking for something in-lined with Iterables.tryFind(fromToMaster, Predicates.isEqualEntry(IGNORE_CASE)).isPresent()

Upvotes: 1

Views: 146

Answers (1)

thrau
thrau

Reputation: 3100

If you want to use guava, you can use the Maps utils, specifically the filterEntries function.

An example to filter only entries where the key does not equal the value (ignoring the case) could look like this

Map<String, String> map = new HashMap<>();
map.put("hello", "helLo");
map.put("Foo", "bar");

Map<String, String> filtered = Maps.filterEntries(map, new Predicate<Map.Entry<String, String>>() {
    @Override
    public boolean apply(Map.Entry<String, String> input) {
        return !input.getKey().equalsIgnoreCase(input.getValue());
    }
});

System.out.println(filtered); // will print {Foo=bar}

However there is no default Predicate in guava's Predicates I know of that does what you want.

Addition:

If you want a validation mechanism without creating a new map, you can use Iterables and the any method to iterate over the entry set of the map. To make the condition more readable I would assign the predicate to a variable or a member field of the class you are working in.

Predicate<Map.Entry<String, String>> keyEqualsValueIgnoreCase = new Predicate<Map.Entry<String, String>>() {
    @Override
    public boolean apply(Map.Entry<String, String> input) {
        return input.getKey().equalsIgnoreCase(input.getValue());
    }
};

if (Iterables.any(map.entrySet(), keyEqualsValueIgnoreCase)) {
    throw new IllegalStateException();
}

or if you need the entry, you can use the Iterables#tryFind method and use the returned Optional

Optional<Map.Entry<String, String>> invalid = Iterables.tryFind(map.entrySet(), keyEqualsValueIgnoreCase);

if(invalid.isPresent()) {
    throw new IllegalStateException("Invalid entry " + invalid.get());
}

Upvotes: 3

Related Questions