Leo
Leo

Reputation: 5235

Identify the Key-Value pair having duplicate values

I have a multimap like below:

{20014=[13123], 20013=[45451, 13123]}

where the keys and values are in String

If there is any duplicate in the value from other key, I have to print that key-value pair. In this case, it will be Key-20013,Value-13123.

How to achieve this? I checked this link but not getting how to get the duplicate pair.

Upvotes: 1

Views: 1275

Answers (2)

mfulton26
mfulton26

Reputation: 31234

You can invert your multimap and, viewed as a map, iterate through its entries:

Multimap<String, String> inverse = Multimaps.invertFrom(multimap, HashMultimap.create());
for (Map.Entry<String, Collection<String>> entry : inverse.asMap().entrySet()) {
    String value = entry.getKey();
    Iterator<String> keysIterator = entry.getValue().iterator();
    assert keysIterator.hasNext() : "there is always at least one key";
    keysIterator.next(); // skip first key
    while (keysIterator.hasNext()) { // each additional key is a duplicate
        String key = keysIterator.next();
        System.out.println(String.format("Key-%s,Value-%s", key, value));
    }
}

Output:

Key-20013,Value-13123

If you are using an ImmutableMultimap then instead of Multimaps.invertFrom(Multimap, M) you can simply use ImmutableMultimap.inverse():

ImmutableMultimap<String, String> inverse = multimap.inverse();

If you simply want a map of duplicated values to their respective keys then you can use Maps.filterValues(Map, Predicate):

Map<String, Collection<String>> keysByDuplicatedValue = Maps.filterValues(inverse.asMap(),
        keys -> keys.size() > 1);

Which will give you a map like below:

{13123=[20014, 20013]}

Upvotes: 1

Nicolas Filotto
Nicolas Filotto

Reputation: 44985

It could be done like this:

// Initialize my multimap
Multimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("20014", "13123");
multimap.put("20013", "45451");
multimap.put("20013", "13123");

// Set in which we store the values to know if they exist already
Set<String> allValues = new HashSet<>();
// Convert the multimap into a Map
Map<String, Collection<String>> map = multimap.asMap();
// Iterate over the existing entries
for (Map.Entry<String, Collection<String>> entry : map.entrySet()) {
    String key = entry.getKey();
    Collection<String> values =  entry.getValue();
    // Iterate over the existing values for a given key
    for (String value : values) {
        // Check if the value has already been defined if so print a log message
        if (!allValues.add(value)) {
            System.out.println(String.format("Key-%s,Value-%s", key, value));
        }
    }
}

Output:

Key-20013,Value-13123

Upvotes: 2

Related Questions