java - 识别具有重复值的键值对

标签 java hashmap guava multimap

我有一个如下所示的多图:

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

键和值在 String 中的位置

如果其他键的值有任何重复,我必须打印那个键值对。在这种情况下,它将是 Key-20013,Value-13123。

如何实现? 我检查了这个 link但不知道如何获得重复对。

最佳答案

可以这样做:

// 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));
        }
    }
}

输出:

Key-20013,Value-13123

关于java - 识别具有重复值的键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38850988/

相关文章:

java - HashMap 优化的影响,将与每个条目关联的哈希代码缓存到其 get 方法

java - 比较段落中的某些字符串(句子的一部分)

java - Guava CacheBuilder 提前驱逐项目

java - 使用 Guava 大小为 "k"的子集

JavaCC:我希望从动态生成的 jj 文件生成 java 类并在运行时编译它们

java - 打印格式化数组

java - 按自定义预定义顺序重新排列 HashMap 键

java - 如何查找映射的键是否作为 groovy 中的属性存在于对象中?

java - 如何选择 Selenium 中的下拉值?

java - 如何在非通用上下文中使用 GuavaOptions?